ios - 如何对 Codable 的所有属性使用 decodeIfPresent?

标签 ios swift codable

如何使 Codable 类对所有属性使用 decodeIfPresent 而无需在自定义初始化程序中键入所有属性?

一个例子:

class Book: Codable {
    var name: String = "Default name"
    var pages: Int = 1

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        for key in container.allKeys {
            // What to do here to call decodeIfPresent?
        }
    }
}

本质上,我想自己复制自动创建的初始化程序,从而改变它的工作方式。

最佳答案

显然这在此时是不可能的(Swift 4)。这是因为 Swift 不支持通过名称动态设置属性。

关于ios - 如何对 Codable 的所有属性使用 decodeIfPresent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126740/

相关文章:

ios - 登录注销 Tableview Swift

ios - 如何在 swift 代码中更改谷歌地图中的位置箭头图标?

ios - 将 NSDate 存储为 CoreData 中的数组

ios - Swift 解码具有多种不同格式的数据类型

ios - 使用 Decodable 解码同一键中的不同对象数组

ios - 在 Swift 中,在 5 秒内(非阻塞)调用一个方法最简单的方法是什么?

ios - 未调用 cellForItemAtIndexPath,原因不明

ios - self.view?.presentScene : unexpectedly found nil while unwrapping an Optional value (Swift)

ios - ARKit 平面检测 - 类型 'ARView' 的值没有成员 'session'

Swift 4 解码简单的根级 json 值