Codable/Decodable should decode Array with Strings

一笑奈何 提交于 2019-12-01 18:48:56

You have defined names as an optional property of Country. If your intention is that this key may not be present in the JSON then use decodeIfPresent:

extension Country {
    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        names = try values.decodeIfPresent([String].self, forKey: .names)
    }
}

This method returns nil if the container does not have a value associated with key, or if the value is null.

But actually you can just omit your custom init(from decoder: Decoder) implementation (and the enum CodingKeys), because that is the default behaviour and will be synthesized automatically.

Remark: An implicit variable error is defined in any catch clause, so

} catch {
    print(error.localizedDescription)
}

can be more informative than just a print("error") (although not in this particular case).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!