How do you design a codable JSON field which can be either an empty string or an int [closed]

≯℡__Kan透↙ 提交于 2019-12-04 15:39:53

I really would suggest changing that web service to return values consistently (and if there is no value for the integer type, don't return anything for that key).

But if you're stuck with this design, you will have to write your own init(from:) which gracefully handles the failure to parse the integer value. E.g.:

struct Person: Codable {
    let name: String
    let age: Int?

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        do {
            age = try values.decode(Int.self, forKey: .age)
        } catch {
            age = nil
        }
    }

}

I'd also advise against using 0 as a sentinel value for "no integer value provided". This is what optionals are for.

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