gpt4 book ai didi

ios - 使用编码协议(protocol)解析 JSON nil 值

转载 作者:可可西里 更新时间:2023-11-01 01:57:24 25 4
gpt4 key购买 nike

假设我有类 Opportunity,带有可选的 code 字段

class Opportunity: Codable {

let id: String
let code: String?

enum OpportunityKeys: String, CodingKey {

case id = "opportunityId"
case code = "opportunityCode"
}

required init(from decoder: Decoder) throws {

let values = try decoder.container(keyedBy: OpportunityKeys.self)

id = try values.decode(String.self, forKey: .id)
if let code = try? values.decode(String.self, forKey: .code) {
self.code = code
}
}
}

有没有比使用 if let 更好地解析 nil 值的方法?

最佳答案

是的,有更好的方法

code = try values.decodeIfPresent(String.self, forKey: .code)

尽可能避免try?

关于ios - 使用编码协议(protocol)解析 JSON nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com