有点被类中最好的插图所困扰...
class AnyDecodableWrapper : Decodable {
static let decodableTypesLookup:[String:Decodable.Type] = [ <-- 'Decodable.Type' here is what's causing the problem
"str": String.self,
"int": Int.self,
"foo": Foo.self
]
enum CodingKeys : String, CodingKey {
case typeKey
case value
}
required init(from decoder: Decoder) throws {
// Get the container for the CodingKeys
let container = try decoder.container(keyedBy: CodingKeys.self)
// Get the key to look up the concrete type
typeKey = try container.decode(String.self, forKey:.typeKey)
// Attempt to get the concrete type from the key
guard let concreteType = AnyDecodableWrapper.decodableTypesLookup[typeKey] else {
value = nil
return
}
// Attempt to decode an instance of the concrete type
let concreteObject = try container.decode(concreteType, forKey: .value)
value = concreteObject
}
let typeKey : String
let value : Any?
}
问题是分配温度concreteObject
的行抱怨以下内容...
对成员'decode(_:forKey :)'的模糊引用
这当然是因为从字典返回的类型是Decodable.Type
,而不是'String.self'之类的东西,因此不确定使用哪个decode
重载。
因此,如果您将具体类型存储在Any.Type
变量中,如何将其传递给正确的解码过载?