I am calling an API and then decoding it with the simplified code below
guard let url = URL(string: "someURL") else {
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
let decoder = JSONDecoder()
if let data = data {
do {
let results = try decoder.decode(Response.self, from: data)
print(results)
} catch {
print(error)
}
}
}
task.resume()
Where Response is my struct seen below
struct Response : Codable {
let response: ResponseContents
}
struct ResponseContents : Codable {
let result : [wantedData]
}
struct wantedData : Codable {
let name: String
}
For the most part this works well however, sometimes the API returns a JSON that does not have a key called name and instead the key is otherName - therefore I get an error saying 'keyNotFound'.
Is there a way I can add a conditional statement in my struct or parsing statement that checks to see if the key is not found and if not it uses another one that I define?