我想扩展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 = ...
我该如何提供要在此处使用的类型?
答案 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)