I am exploring a COVID-19 API via RapidAPI and obtained the following response from an endpoint:
[0:
"country":"Canada"
"provinces":[
0:{
"province":"Alberta"
"confirmed":754
"recovered":0
"deaths":9
"active":0
}...etc]
"latitude":56.130366
"longitude":-106.346771
"date":"2020-04-01"
}
]
My goal is to extract the ‘provinces’ data, so in Xcode I have created models as follows:
struct Nation: Codable {
let name: String
let regions: [Region]
}
struct Region: Codable {
let name: String
let confirmedCases: Int
let recoveredCases: Int
let fatalities: Int
let activeCases: Int
}
While I believe these models are set up correctly, the parsing fails unless I comment out the ‘regions’ variable in Nation:
struct Nation: Codable {
let name: String
//let regions: [Region]
}
As a result, I can print the country’s name, but not the provinces. This leads me to think there’s an issue with my model structure. What might I be missing? I’ve referred to examples, and this setup should function correctly.
UPDATE: Here’s more code for context:
override func viewDidLoad() {
super.viewDidLoad()
Service.shared.fetchInfo(url: "url", hostName: "host", apiKey: "12345", requiresKey: true) { response in
if let responseData = response {
if let nations = try? JSONDecoder().decode([Nation].self, from: responseData) {
// Assign the first province's name to a variable
let province: String = nations[0].regions[0].name
self.provinceOutput = province
}
DispatchQueue.main.async { [weak self] in
// Output the province name
print(self?.provinceOutput)
}
}
}
}