Ever faced a situation where your app started crashing out of nowhere, which upon investigation yields that the backend provided a value for certain enum based field that does not exist inside the enum in code?
Consider the following example:
This outputs the following:
Ohhh I love some Tea
But what if we change favouriteBeverage in the JSON data from Tea to Juice(a value that does not exist inside the enum, Beverage ) ?
__lldb_expr_5/MyPlayground.playground:20: Fatal error: ‘try!’ expression unexpectedly raised an error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: “favouriteBeverage”, intValue: nil)], debugDescription: “Cannot initialize Beverage from invalid String value Juice”, underlyingError: nil))
Focus on the part of the message: “Cannot initialize Beverage from invalid String value Juice”
If it was an actual app instead of a playground code, the app would have crashed. So, how do we take care of the fact that even if the backend sends an invalid value in the response, our app should be able to handle it instead of outright crashing?
One of the ways, and my personal favourite: Incorrect Enum Fallback Mechanism
It says mechanism but is more or less a protocol that takes care of everything. So, here we go ….
We mainly need our Codable enum to conform to IncorrectEnumFallbackMechanism protocol and provide any case of the enum to be the fallbackForIncorrectEnumValue . Confused? Here’s how the updated enum( Beverage one) will look like:
So this time, instead of crashing, our favouriteBeverage will be ….. a weird one? SomeWeirdBeverage
Wait! What is that?
No matter what the backend sends us as favouriteBeverage , we will be able to handle it, or drink it, whatever!
So our complete code will now look like this:
There might be other ways out there but like I said, this is my favorite!