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

标签 ios json swift swift4

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

相关文章:

作为公司而不是个人进行 iOS 代码签名

iphone - 从上到下的渐变切割

ios - 返回 xcode/swift/ios 项目 - 突然得到 "no such module"

javascript - 内容:encoded: in JSON with JQuery

ios - 折叠时如何更改图像单元格?

ios - 动态管理标签文本无法正常工作

c++ - 将 JSON 对象作为 Boost 中的键值对插入现有 JSON 对象中

jquery - jqGrid不显示任何数据

swift - 在 SceneKit 中按所需方向旋转后如何平移相机节点位置?

ios - 使用 CGColorSpaceCreateDeviceGray() 将彩色 UIImage 转换为灰度