I'm using someone else's API. It is returning me JSON like this:
[{"ID": 123,
"Name": "My Game Api",
"Type": "Racing",
"Num": 0,
"Country": "England"
}]
I define a struct to parse JSON, like this:
struct MyResult : Decodable{
var ID : Int?
var Name : String?
var Type : String?
var Num : Int?
var Country : String?
}
// Using..
let games = try JSONDecoder().decode([MyResult].self, from: data!)
Of course Xcode gives me an error:
Type member may not be named 'Type', since it would conflict with the 'foo.Type' expression.
I did not write the API. If I change the name of the variable Type, I can not read the value.
Can I use Decodable Struct without modifying the API?
You can use like below :
struct MyResult : Decodable {
var ID : Int?
var Name : String?
var type : String?
var Num : Int?
var Country : String?
private enum CodingKeys : String, CodingKey {
case ID, Name, type = "Type", Num, Country
}
}
Try to follow the comments posted by Hamish