假设我有类 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/