How do you design a codable JSON field which can b

2019-04-14 02:09发布

问题:

How do you handle a field of a codable struct from JSON which can be either an empty string or an int? I tried using the data type any but that does not conform to codable. I think that if it does not have a value then it returns an empty string or otherwise, it returns an int. I am using Swift 4 and XCode 9. Thanks in advance

回答1:

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.