Swift 可编码,默认值为 Class 属性 当 JSON 中缺少密钥时

Swift codable, Default Value to Class property when key missing in the JSON

如您所知,Codable 是 swift 4 中的新内容,所以我们将从旧的模型初始化过程转移到这个。通常我们使用下面的Scenario

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可能会丢失,所以我们给默认Value为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)
    }