I have a Codable
class with a variable that holds a dictionary with String
keys and values that may be String
s, Int
s or custom structs conforming to Codable
. My question is:
How do I define a dictionary with values that are Codable
?
I hoped it would be enough to say
var data: [String: Codable] = [:]
but apparently that makes my class no longer conform to Codable
. I think the problem here is the same as I had here, where I am passing a protocol rather than an object constrained by the protocol
Using JSON Encoder to encode a variable with Codable as type
So presumably I would need a constrained generic type, something like AnyObject<Codable>
but that's not possible.
EDIT: Answer
So since this can't be done as per the accepted answer, I am resorting to a struct with dictionaries for each data type
struct CodableData {
var ints: [String: Int]
var strings: [String: String]
//...
init() {
ints = [:]
strings = [:]
}
}
var data = CodableData()
Codable
as an existential type in the dictionary. You're right in that you need to constrain the type to something, but evenAnyObject<Codable>
wouldn't be it — you need something concrete, likeInt
orString
. Are there limits on the types your dictionary will contain? And what do you expect to have happen on decode? – Itai Ferber