Simple Swift tip #1: Deal with bad JSON

Imagine that in your new job, the RESTFul API that will be your friend in the next 6 months isn’t correctly designed. And you receive a different data structure for the same value, depending on external factors that you can’t control. For example, you’ll receive every text content translated into two languages but if one is missing, you’ll receive only the default language.

As the previous JSON shows, we could receive a translated string in multiple forms, as a dictionary or as a string. How to deal with that? First let’s try with the straight solution:

and this code will fail because a string will be received when a dictionary is expected. In order to improve it, let’s create a custom decoder:

We create a Decodable extension to our TranslatedText and try to parse the content as a single string or a dictionary. Neat and simple. The new Codable implementation included in Swift 4 gives us a nice surprise again.

I hope this tip saves you some time :)