I'm currently learning swift and i'm trying to make a api call that can send two different responses:
First one is:
{
"data": {
"id": 1
},
"error": null
}
Second one is:
{
"data": null,
"error": " Password not matching"
}
So in the first json the data is a nested container, and in the second one its not.
What i have so far is the following, which works fine for the first case, but i have no idea how to change my struct to handle the second case. Any hits/ideas would be greatly appreciated:
struct ApiData {
let userID: Int?
let error: String?
}
extension ApiData: Decodable{
enum CodingKeys: String, CodingKey {
case data = "data"
case userId = "id"
case error = "error"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
let data = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
let userId = try data.decode(Int.self, forKey: .userId)
self.init(userID: nil, error: nil)
} catch let error {
print(error)
throw error
}
}
}
If i try in the do block to decode the error case, when received the first type of response, will get a "Data is not in the correct format error" thrown.