Use an Enum to Decode JSON in Swift

It really makes sense!

Steven Curtis
4 min readApr 6

--

Photo by Michael Dziedzic on Unsplash

Before we start

Difficulty: Beginner | Easy | Normal | Challenging<br/>

Prerequisites:

  • There is a less simpler of decoding JSON

Keywords and Terminology:

Decodable: A type that can decode itself from an external representation

JSON: JavaScript Object Notation, a lightweight format for storing and transporting data

The project

This article uses a Playground and in order to avoid downloading from the Network or similar this is using a hard-coded JSON String:

let json = """
{
"people":
[
{
"name": "Dr",
"profession": "DOCTOR"
}
,
{
"name": "James",
"profession": "ACTOR"
}
]
}
"""

This JSON String can be validated by using one of the available online parsers (I use http://json.parser.online.fr)

The first attempt

The JSON is an Array, with a name and profession each defined as a String.

The basic structs need to both conform to Decodable so it can be decoded.

struct People: Decodable {
let people: [Person]
}

struct Person: Decodable {
let name: String
let profession: String
}

which can then be decoded using the JSONDecoder() and then for simplicity this is printed to the screen:

let decoder = JSONDecoder()
let person = try! decoder.decode(People.self, from: json.data(using: .utf16)!)
print (person)

The force unwraps can be seen as bad form here, and I’ve written a whole article about avoiding them but in this case I’ve gone for force-unwrapping using the try as this (in the case of an error) will display that error in the console — and unwrapping the data provides an early indication that there is something wrong. This isn’t production code, remember!

This gives the following output to the console:

People(people: [__lldb_expr_57.Person(name: "Dr", profession: "DOCTOR")…

--

--