如何从字典扩展Decodable以进行初始化?

时间:2019-02-22 14:53:11

标签: swift extension-methods decodable

我想扩展Decodable,以便可以从值字典创建Codable类的新实例。

extension Decodable {
    init(from dictionary: [String : Codable]) throws {
        let data = try JSONSerialization.data(withJSONObject: dictionary, options: [])
        let newSelf = try JSONDecoder().decode(self.type, from: data)

        self = newSelf
    }
}

Value of type 'Self' has no member 'type'开头的行出现错误let newSelf = ...

我该如何提供要在此处使用的类型?

1 个答案:

答案 0 :(得分:2)

self.type必须是具体类型,而不是协议。而且您仍然无法创建Decodable的实例。

您可以做的是创建一个通用的decode方法,该方法以字典为参数

func decode<T : Decodable>(from dictionary: [String : Decodable]) throws -> T {
    let data = try JSONSerialization.data(withJSONObject: dictionary)
    return try JSONDecoder().decode(T.self, from: data)
}


struct Person : Decodable {
    let name : String
    let age : Int
}

let dict : [String:Decodable] = ["name" : "Foo", "age" : 30]

let person : Person = try! decode(from: dict)