Swift 4 Codable - API provides sometimes an Int sometimes a String

这一生的挚爱 提交于 2019-12-03 22:48:18

you may implement your own decode init method, get each class property from decode container, during this section, make your logic dealing with wether "rating" is an Int or String, sign all required class properties at last.

here is a simple demo i made:

class Demo: Decodable {
    var test = 0
    var rating: String?

    enum CodingKeys: String, CodingKey {
        case test
        case rating
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let test = try container.decode(Int.self, forKey: .test)
        let ratingString = try? container.decode(String.self, forKey: .rating)
        let ratingInt = try? container.decode(Int.self, forKey: .rating)
        self.rating = ratingString ?? (ratingInt == 0 ? "rating is nil or 0" : "rating is integer but not 0")
        self.test = test
    }
}

let jsonDecoder = JSONDecoder()
let result = try! jsonDecoder.decode(Demo.self, from: YOUR-JSON-DATA)
  • if rating API's value is normal string, you will get it as you wish.
  • if rating API's value is 0, rating will equal to "rating is nil or 0"
  • if rating API's value is other integers, rating will be "rating is integer but not 0"

you may modify decoded "rating" result, that should be easy.

hope this could give you a little help. :)

for more info: Apple's encoding and decoding doc

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