Hey I have this Json for Example:
{"v":{"value1":1548303671,"value2":"invalid","value3":"invalid"}}
And the model class:
struct VersionApi: Decodable {
let data: NestedData?
let v: [String:Int?]
enum CodingKeys: String, CodingKey {
case data = "data"
case v = "v"
}
}
When trying to decode I get this error message:
debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil)
I know what it means but I don't know a solution.
I need a dictionary with Ints in this format: [String:Int?]
. I tried to write a custom initializer like that:
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
data = try values.decode(NestedData, forKey: .data)
let vID: [String:Any] = try values.decode([String:Any].self, forKey: .v)
v = try values.decode([String:Int?].self, forKey: .v)
}
I then wanted to go through the dictionary and if Any
is not Int
I wanted it to set to nil
. But this does not work as no candidates produce the expected type:
No 'decode' candidates produce the expected contextual result type '[String : Any]'
How can I set Int to nil if the value is not an Int?