Fall 2023 | Vin Bui

In the previous section, we mentioned how data that is sent across the internet is represented as JSON. In this section, we will discuss how to decode JSON data and use it in our Swift code.

What is Codable?

In Swift, there are two protocols that our model structs/classes must conform to in order to be decoded: Decodable and Encodable. However, we commonly use the protocol Codable instead which essentially means that we are conforming to both protocols.

These protocols are very powerful and allow us to customize our own JSON decoder and encoder. For the scope of this course, we will only touch the bare surface.

Structuring our Data Model

Consider the following JSON data representing a student:

    "age": 19,
    "classes": [
	"CS 1998",
	"PHYS 2213"
    "first_name": "Vin",
    "last_name": "Bui",
    "major": "Info Sci"

This is the information that we are given from the backend that represents a student. As a frontend developer, we need to make sure that both the frontend and the backend agree on one schema. Given this data, we have to decide on how to create our data model objects.

There are five keys in this JSON here: age, classes, first_name, last_name and major. Normally, we want the name of our properties to match exactly with the keys in the JSON (although there is a way to customize this). Once we have the names down, we need to determine the type of each property. Notice that the value for age does not have quotes around it so it is not a String. Also notice that the value for classes contains square brackets, indicating that it is an array where each element is a String. This gives us the following Student model:

struct Student: Codable {
    let age: Int
    let classes: [String]
    let firstName: String
    let lastName: String
    let major: String

Notice how the JSON has the key first_name and last_name, but in the model we use firstName and lastName. Although JSON is typically represented with camelCase, there are times when it may use snake_case (for example in our course). Since Swift's convention is to use camelCase, it has a built-in decoder/encoder that provides a neat way to deal with this, which we will look at in the next section.

Last updated