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

寵の児 提交于 2019-12-22 08:57:48

问题


As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following 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
    }
}

In the JSON cashierType Key may missing, so we giving the default Value as 0

Now while doing this with Codable is quite easy, as following

class LoginModal: Coadable
{    
    let cashierType: NSNumber
    let status: NSNumber
}

as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.

Thanks


回答1:


Use init(from decoder: Decoder) to set the default values in your model.

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
    }
}

Data Reading:

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)
    }


来源:https://stackoverflow.com/questions/53237085/swift-codable-default-value-to-class-property-when-key-missing-in-the-json

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