如您所知,Codable 是 swift 4 中的新内容,因此我们将从旧的模型初始化过程转移到这个。通常我们使用以下场景
class LoginModal
{
let cashierType: NSNumber
let status: NSNumber
init(_ json: JSON)
{
let keys = Constants.LoginModal()
cashierType = json[keys.cashierType].number ?? 0
status = json[keys.status].number ?? 0
}
}
JSON 中的 cashierType
Key 可能会丢失,因此我们将默认值设为 0
现在使用 Codable 执行此操作非常简单,如下所示
class LoginModal: Coadable
{
let cashierType: NSNumber
let status: NSNumber
}
如上所述,键可能会丢失,但我们不希望模型变量是可选的,那么我们如何使用 Codable 实现这一点。
谢谢
最佳答案
使用 init(from decoder: Decoder)
设置模型中的默认值。
struct LoginModal: Codable {
let cashierType: Int
let status: Int
enum CodingKeys: String, CodingKey {
case cashierType = "cashierType"
case status = "status"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
}
}
数据读取:
do {
let data = //JSON Data from API
let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
print("\(jsonData.status) \(jsonData.cashierType)")
} catch let error {
print(error.localizedDescription)
}
关于ios - Swift 可编码,当 JSON 中缺少键时,类属性的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53237085/