Swift 4 decoding JSON using Codable

Introduction

Swift 4 was released along with iOS11 last September. It focuses on
improving the stability of the ABI (application binary interface). This meant
less drastic changes as compared to when we made the move from Swift 2 to Swift 3.
My favourite new feature in Swift 4 is the addition of the Codable extension.
Codable makes it easy to parse JSON into structs and use throughout your code,
no more messing around with dictionaries. Swift 4.1 makes some changes to the Codable
extension that make it even more powerful, but more on that later.

Prerequisites

  • Xcode 9.3+
  • Swift 4.1+
It’s not a requirement but cloning the completed example project may make the tutorial easier to follow. Example Project

Main content

Understanding your JSON

For this tutorial I will be reading in JSON from a local file. The principles of using the Codable extension do not change whether you are reading in data from a local file or one on a server.
The stub data within the project contains a file londonWeather.json This is a real response from the open weather map API.

There are two key concepts in understanding your JSON file: you need to understand what is a key/value pair and what is a key/object pair. The stub data contains plenty of examples of either of these. If we look at the highest level of the object the first two keys are examples of key/value.

"id":2643743,
"name":"London"

The key maps directly to the value, key being the string on the left of the colon and the value being the type (such as string integer) on the right.
Key/object pairs are those that don't map directly to types in JSON. The object itself usually contains a set of key/values.

"coord": {
  "lon":-0.13,
  "lat":51.51
},

The key in the above example is coord but within the object there are two key/value pairs. Another example of a key/object pair is one that maps to an array. The principle is the same here but it can map to more than one object.

"weather": [{
   "id":300,
  "main": "Drizzle",
  "description": "light intensity drizzle",
  "icon":"09d"
}]

Converting your JSON to structs
The next task is to create your model. Start by taking your high level object. In the example project this is within the CurrentWeather.swift file.

struct CurrentWeather: Codable { //1
    // 2
    let coord: Coord
    // 3
    let weather: [WeatherDetails]