如何将decodeIfPresent用于Codable的所有属性?

时间:2017-11-05 21:19:56

标签: 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?
        }
    }
}

本质上,我想自己复制自动创建的初始化程序,使其改变它的工作原理。

1 个答案:

答案 0 :(得分:0)

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