I’m working with a COVID-19 data API and running into problems when trying to decode nested arrays. The API returns data that looks like this:
[
{
"country": "United States",
"states": [
{
"state": "California",
"cases": 1250,
"cured": 45,
"fatalities": 12,
"current": 1193
}
],
"lat": 39.8283,
"lng": -98.5795,
"timestamp": "2020-04-15"
}
]
I created these data models:
struct Nation: Codable {
let country: String
let states: [State]
}
struct State: Codable {
let state: String
let cases: Int
let cured: Int
let fatalities: Int
let current: Int
}
The weird thing is that JSON parsing only works when I remove the nested array property:
struct Nation: Codable {
let country: String
// let states: [State] // commenting this out makes it work
}
Here’s my parsing code:
override func viewDidLoad() {
super.viewDidLoad()
APIService.shared.fetchData(endpoint: "covid-data", apiKey: "abc123") { responseData in
guard let responseData = responseData else { return }
do {
let nations = try JSONDecoder().decode([Nation].self, from: responseData)
let firstState = nations[0].states[0].state
self.selectedState = firstState
DispatchQueue.main.async {
print(self.selectedState)
}
} catch {
print("Decoding failed: \(error)")
}
}
}
What could be causing this issue with the nested array decoding?