属性 可以是integer 也可以是bool 时解析什么对象?

What parsing object when property can be integer or bool?

有时服务器将 属性 作为 bool (true, false) 发送给我。 有时服务器将 属性 作为整数 (0,1) 发送给我。

如何通过 Swift 4 中的标准 Decodable 解码这种情况?

例子。 我有:

final class MyOffer : Codable {
    var id = 0
    var pickupAsap: Int?

    enum CodingKeys: String, CodingKey {
         case id
         case pickupAsap = "pickup_asap"
    }
}

来自服务器的响应是:

1) "pickup_all_day":正确,

2) "pickup_all_day": 0

你可以实现你自己的 decode init 方法,从解码容器中获取每个 class 属性,在这个部分,让你的逻辑处理 "asap" 是 Int 还是 Bool , 最后签署所有必需的 class 属性。

这是我制作的一个简单演示:

class Demo: Decodable {
    var id = 0
    var pickupAsap: Int?

    enum CodingKeys: String, CodingKey {
        case id
        case pickupAsap = "pickup_asap"
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let id = try container.decode(Int.self, forKey: .id)
        let pickupAsapBool = try? container.decode(Bool.self, forKey: .pickupAsap)
        let pickupAsapInt = try? container.decode(Int.self, forKey: .pickupAsap)
        self.pickupAsap = pickupAsapInt ?? (pickupAsapBool! ? 1 : 0)
        self.id = id
    }
}

模拟数据:

 let jsonInt = """
{"id": 10,
 "pickup_asap": 0
}
""".data(using: .utf8)!

let jsonBool = """
{"id": 10,
 "pickup_asap": true
}
""".data(using: .utf8)!

测试:

let jsonDecoder = JSONDecoder()
let result = try! jsonDecoder.decode(Demo.self, from: jsonInt)
print("asap with Int: \(result.pickupAsap)")

let result2 = try! jsonDecoder.decode(Demo.self, from: jsonBool)
print("asap with Bool: \(result2.pickupAsap)")

输出:

asap with Int: Optional(0)
asap with Bool: Optional(1)

更多信息:Apple's encoding and decoding doc