If I have a JSON Codable object in Swift that looks like:
struct IceCreamStore: Codable {
let iceCreams: [IceCream: Int]
}
enum IceCream: String, Codable {
case chocolate, vanilla
}
And I accidentally encoded a strawberry
field from a new version of the app, so that the dictionary now has a strawberry
field in it, that this older version of the app doesn't know how to deal with (and thus can't decode it and errors), is there a way to conditionally decode it and just ignore that strawberry
value? I tried using CodingKeys and decoding it as a [String: IceCreamInfo]
instead manually, but no dice, still won't decode as that. I don't want to add strawberry manually as a value for a number of reasons but just consider those academic.
It's basically trying to ingest:
{
"chocolate": 8,
"vanilla": 4,
"strawberry": 3
}
When it doesn't know how to deal with strawberry, and I want to just have it ignore the strawberry.
Like, in my head I want to do:
let container = try decoder.container(keyedBy: CodingKeys.self)
let manualDictionary = try container.decode([String: Int].self, forKey: .iceCreams)
var realDictionary: [IceCream: Int] = [:]
for key, value in manualDictionary {
guard let iceCream = IceCream(rawValue: key) else { continue }
realDictionary[iceCream] = value
}
self.iceCreams = realDictionary
But that's not working (it won't let me decode it as a [String: Int]
).
What's the exact JSON you're trying to decode with the above code?