Use an Enum to Decode JSON in Swift
It really makes sense!
4 min readApr 6, 2023
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.