Decoding an Array with Swift4 Codable

此生再无相见时 提交于 2019-12-05 17:22:47

You decoded the weather key incorrectly. It's a top-level key so you don't need to create a subcontainer. This is enough:

self.weather = try container.decode([WeatherObj].self, forKey: .weather)

However I'd actually recommend that you create a private struct that stays very close to the JSON to ease the decoding process. Then you can pick off the pieces you want to initialize the data model:

struct Response: Codable {
    var name: String
    var code: Int
    var temp: Double
    var pressure: Int
    var weather: [WeatherObj]

    // This stays as close to the JSON as possible to minimize the amount of manual code
    // It uses snake_case and the JSON's spelling of "cod" for "code". Since it's private,
    // outside caller can never access it
    private struct RawResponse: Codable {
        var name: String
        var cod: Int
        var main: Main
        var weather: [WeatherObj]

        struct Main: Codable {
            var temp: Double
            var pressure: Int
        }
    }

    init(from decoder: Decoder) throws {
        let rawResponse = try RawResponse(from: decoder)

        // Now pick the pieces you want
        self.name     = rawResponse.name
        self.code     = rawResponse.cod
        self.temp     = rawResponse.main.temp
        self.pressure = rawResponse.main.pressure
        self.weather  = rawResponse.weather
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!