如何扩展 Decodable 以从字典初始化?
How can I extend Decodable to initialise from dictionary?
我想扩展 Decodable,这样我就可以从值字典中创建 Codable class 的新实例。
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
}
}
我在以 let newSelf = ...
开头的行中收到错误 Value of type 'Self' has no member 'type'
我应该如何提供要在此处使用的类型?
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)
我想扩展 Decodable,这样我就可以从值字典中创建 Codable class 的新实例。
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
}
}
我在以 let newSelf = ...
Value of type 'Self' has no member 'type'
我应该如何提供要在此处使用的类型?
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)