Decoding Arrays in Swift
Written by Team Kodeco
Written by Team Kodeco
When decoding arrays in Swift, you are converting a JSON-style array data structure into Swift objects.
To decode an array, you use the decode method of the JSONDecoder class, passing in the type of the array as a generic parameter. For example, Consider this JSON data:
[
{
"make":"Tesla",
"model":"Model S",
"year":2020,
"color":"Red"
},
{
"make":"Toyota",
"model":"Camry",
"year":2019,
"color":"Silver"
}
]
Here’s the struct that you’ll use to decode the data:
import Foundation
struct Car: Codable {
let make: String
let model: String
let year: Int
let color: String
}
And here’s the code to decode the data:
let jsonData = """
[
{
"make": "Tesla",
"model": "Model S",
"year": 2020,
"color": "Red"
},
{
"make": "Toyota",
"model": "Camry",
"year": 2019,
"color": "Silver"
}
]
""".data(using: .utf8)!
let decoder = JSONDecoder()
let cars = try decoder.decode([Car].self, from: jsonData)
print(cars)
// Output: [Car(make: "Tesla", model: "Model S", year: 2020, color: "Red"),
// Car(make: "Toyota", model: "Camry", year: 2019, color: "Silver")]
Prev chapter
1.
Coding & Decoding Data in Swift
Next chapter
3.
Handle Custom Keys & Missing Values while Decoding in Swift