Improved Codable with keyDecodingStrategy

Dealing with Codeable in Swift 4 wasn’t a pleasant experience. Backend developers never understood why I hated snake_case so much. I pushed and pushed for camelCase but it just never happened. (They must have their reasons)

Snake_Case and Codeable just didn’t mix. I wasn’t prepared to go snake_case solely due to the unwritten rule that camelCase is the standard naming convention within Swift. Codable couldn’t convert between the two. To get around this problem you had to create your CodingKeys mapping to match things up.

Now with Swift 4.1  Apple has solved the problem. This comes in the form of keyDecodingStrategy & keyEncodingStrategy that lives within the JSONDecoder class. Therefore you can now easily convert camelCase into snake_case.

So we first have a JSON string, this is normally fetched from a server in the cloud. Notice we have a snake case top_trump_score.

Then we convert this JSON string to a Data object. So we can use JSONDecoder.

Next, we are going to create a model that converts the JSON into an array.

Then we decode the jsonData with the following syntax

A brief explanation of whats happening here:

  1. Create an instance of JSONDecoder
  2. Tell the decoder that we expect snake_case in the data
  3. Decode the jsonData object to the Car Struct we created
  4. If error print error. You would normally handle this error better