I'm looking at this API for covid19 on RapidAPI. I Tested the endpoint and it showed this result:
[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"
}
]
Pretty straight forward. I want to parse the "provinces" segment, so in xcode I set up a couple models like this:
struct Country: Codable{
let country: String
let provinces: [Province]
}
struct Province: Codable{
let province: String
let confirmed: Int
let recovered: Int
let deaths: Int
let active: Int
}
I believe this is correct, but it won't parse. It only works when I comment out this bit:
struct Country: Codable{
let country: String
//let provinces: [Province]
}
meaning I can print out the name of the country, but only when the provinces object is commented out. This makes me think that there is something wrong with my model. What am I doing wrong here? I've looked up other examples and this should be working... I'm pretty sure.
EDIT: I'll add a bit more code to make it clearer what I'm doing:
override func viewDidLoad() {
super.viewDidLoad()
Service.shared.getInfo(requestURL: "url", host: "host", key: "12345", needsKey: true) { data in
if let data = data{
if let p = try? JSONDecoder().decode([Country].self, from: data){
//get the data and set it to a string
let provinceName: String = p[0].provinces[0].province
self.provinceStr = provinceName
}
DispatchQueue.main.async {
[unowned self] in
//print the string
print(self.provinceStr)
}
}
}
}
from the printout, this is the data structure you should be using:
struct Country: Codable {
let country, code: String
let confirmed, recovered, critical, deaths: Int
let latitude, longitude: Double
let lastChange, lastUpdate: Date // <-- or String
}