0

I use 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?

Zebedee
  • 420
  • 2
  • 7
  • 19
  • 5
    Compare https://stackoverflow.com/q/44396500/2976878. You should use `lowerCamelCase` property names as is Swift convention; and map to your JSON keys in a custom `CodingKeys` enum. – Hamish Sep 28 '17 at 18:18
  • https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types#2904057 – Slayter Sep 28 '17 at 18:21
  • 1
    Also, unrelated, but do all your properties really need to be optional? Is it legal for your JSON to not contain keys for *any* of them? – Hamish Sep 28 '17 at 18:22
  • 3
    As @Hamish has stated, you should be using camelCase variable names and a `CodingKeys` enum. That being said, you can probably still use `Type` as a variable name by surrounding it's declaration with back-ticks (`). I don't recommend this, though. – dalton_c Sep 28 '17 at 18:29

1 Answers1

1

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

Vini App
  • 7,339
  • 2
  • 26
  • 43
  • 3
    It is Swift convention to name your types starting with a lowercase letter. And just do the same you did for "Type" for the other properties – Leo Dabus Sep 28 '17 at 19:00
  • 2
    btw you should declare all you struct properties as constants using let and probably none of them needs to be optional – Leo Dabus Sep 28 '17 at 19:02