I have a class Codablewith a variable that contains a dictionary with Stringkeys and values, which may be Strings, Intor custom structures that are appropriate Codable. My question is:
How to define a dictionary with values Codable?
I was hoping it would be enough to say
var data: [String: Codable] = [:]
but obviously my class no longer matches Codable. I think the problem here is the same as mine here, where I pass the protocol and not the object limited by the protocol
Using JSON Encoder to Encode a Variable with Codable as a Type
So, suppose I need a limited generic type, something like AnyObject<Codable>, but that is not possible.
EDIT: answer
Since this cannot be done in accordance with the accepted answer, I resort to a structure with dictionaries for each data type
struct CodableData {
var ints: [String: Int]
var strings: [String: String]
init() {
ints = [:]
strings = [:]
}
}
var data = CodableData()
source
share