It’s not a requirement but cloning the completed example project may make the tutorial easier to follow. Example Project
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 mapAPI.
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.
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.
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.
"description": "light intensity drizzle",
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.