I'm not sure how to use JsonDecoder with an optional enum.
This scenario would occur when the client and server agree on an enum, then the server starts returning an additional enum value.
//e.g. enum defined on deployed app
enum ColorType: Int, Codable {
case red = 0
case green = 1
}
struct ColorResponse: Codable {
var color: ColorType?
}
//server starts returning new enum case blue = 2
let jsonString = "{ \"color\": 2 }"
let jsonDecoder = JSONDecoder()
let jsonData = jsonString.data(using: .utf8)
let response = try? jsonDecoder.decode(ColorResponse.self, from: jsonData!)
My assumption was that response would be an instance of ColorResponse with color == nil
Instead, JsonDecoder throws a DataCorrupted error
"Cannot initialize ColorType from invalid Int value 2"
I don't want to lose strong typing by changing ColorResponse to var color: Int
Thanks,
casey