swift - 可编码 : give a default value to a new non-optional property

标签 swift

<分区>

如果我们对符合 Codable 的类的对象进行编码,并希望使用具有新属性的新类代码来解码这些对象,那么需要什么代码才能使该新属性成为非- 可选,并为其属性赋予默认值?

老类:

class Item: Codable {
    let id: String
}

新类:

class Item: Codable {
    let id: String
    let title: String
}

当使用新格式的代码解码以旧格式保存的对象时,将找不到 title 属性,并且解码将不起作用。

我们可以通过使 title 成为可选的 String? 来解决这个问题。

但我们如何才能将 title 保持为非可选 String,并在解码每个对象时为其赋予默认值?

PS:这是完整的代码。没有指定编码 key ,也没有编写来自解码器的自定义初始化。

最佳答案

你可以实现 required init 并给它一个默认值:

required init(from decoder: Decoder) throws {

    let container = try decoder.container(keyedBy: CodingKeys.self)

    let title = try container.decodeIfPresent(String.self, forKey: .title) ?? "Default title"
    self.title = title

    let baseDecoder = try container.superDecoder(forKey: .id)

    try super.init(from: baseDecoder)
}

关于swift - 可编码 : give a default value to a new non-optional property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760875/

相关文章:

ios - 无法在 Xcode 11 beta 中选择自定义字体?

ios - Swift:过滤 tableView 中的 SwiftyJSON 数据

ios - JsqMessageViewController View 仅显示单行文本

xcode - 导航 Controller 崩溃应用程序

ios - 如何判断 child 是否为零

ios - 用户登录后更新 Root View Controller + iOS 13 及更高版本

ios - 是否可以在 UITextview 链接选择上设置清除颜色?

swift - 为什么在 Swift 中两个不同的数组字面量彼此相等?

swift - 从观察者更新 TableView Cell UI

ios - 将位置坐标保存到核心数据 - Swift 3