-2

I'm fetching data from an API but this API has a small problem inside location JSON Object, it contains a variable called postcode and this variable can be either a String or a Int.

I have to handle this problem locally, If I set var postcode: String I get an error when this value is Int and if I set var postcode: Int I get an error when this value is a String

so I tried to set var postcode: Any but the following problem occurs...

enter image description here

it when I set this value it doesn't conform to Codable protocol...

when I return the way it was before....

enter image description here

I got no errors BUT it doesn't handle my problem with the API.

what am I missing here?

thank you in advance for the answers..

Lucas
  • 746
  • 8
  • 23
  • See this answer: https://stackoverflow.com/questions/49717575/decodable-and-json-2-datatypes-for-same-variable – Chris Shaw Mar 13 '19 at 23:00
  • 1
    We can describe how you can handle this (a variation of the answer that Chris Shaw shared with you), but the best solution is to fix whatever produces this JSON to return numeric only postal codes as a string (with quotes) as well. It seems unfortunate to contort yourself to work around a poorly designed API if you don’t have to. (But, then again, maybe you’re stuck with this API.) – Rob Mar 13 '19 at 23:40
  • FWIW, it’s dangerous to assume that a numeric postal code should be a five digit number with leading zeros. Some countries have numeric only postal codes with less than five digits. – Rob Mar 13 '19 at 23:45

1 Answers1

0

Since you can always convert Int to String, why not store postcode as String? Then, depending on how you deal with it in your app, provide a computable property to give you back whatever type you need.

Ron
  • 660
  • 1
  • 5
  • 10
  • That’s fine, but if the JSON has postal codes with the same key, e.g. `postcode`, with some instances as as strings (with quotes) and others as integers (without quotes), then simple `JSONDecoder` approach won’t work. You’d have to write your own [`init(from:)`](https://developer.apple.com/documentation/swift/decodable/2894081-init) as contemplated in [Encoding and Decoding Custom Types](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) to handle these scenarios. Or just fix whatever is preparing this JSON. – Rob Mar 13 '19 at 23:37
  • True. I made the naive assumption that the trip from JSON was one-way and that once the data is stored in the app the source no longer matters. – Ron Mar 13 '19 at 23:48