Posts

Post not yet marked as solved
5 Replies
1.8k Views
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 appenum ColorType: Int, Codable { case red = 0 case green = 1}struct ColorResponse: Codable { var color: ColorType?}//server starts returning new enum case blue = 2let 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 == nilInstead, 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: IntThanks,casey
Posted
by kcchesnut.
Last updated
.