Little stumped by something that's best illustrated with a class...
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?
}
The problem is the line assigning the temp concreteObject
complains with the following...
Ambiguous reference to member 'decode(_:forKey:)'
This is of course because the type returned from the dictionary is Decodable.Type
and not something like 'String.self' thus it's not sure which decode
overload to use.
So if you have the concrete type stored in a variable of Any.Type
, how can you pass that to the correct decode overload?