Server returns two different types for one value

Hello. I have the following problem. https://coinmarketcap.com returns Double and Int types for total supply value. I need to show it in label, but it displays as "Int(12344)" and "Double(2455.5)".

I used this SO solution for decoding. Could you please say how to remove types and display only values?

There's no need to distinguish between Int and Double, as JSON is transmitted untyped. You should be able to parse all values as a Double. Do you have to make this distinction for some reason?

1 Like

Furthermore, unless your integer has a really large magnitude (~2^53 large), you shouldn't lose any precision using Double.

That said, to answer your original question, you can override how print and (default) string interpolation handle your instance using CustomStringConvertible.

1 Like

Thank you for help! I didn't know that we can use Double, if a response value comes in Int and Double types. Now everything works fine :partying_face:

I've seen this before, that may be related to how JSONSerialization works internally, this is explained in detail on https://bugs.swift.org/browse/SR-12974

1 Like

JSON doesn't have a concept of neither double or integer. In only deals with the Javascript type Number. This is because JSON is really Javascript, and Javascript doesn't have a notion of integers. When decoding JSON using JSONDecoder and Decodable, Swift will parse any number as whatever you try to decode is as.

However, when using (NS)JSONSerialization, it will produce a [String: Any] output, where each value is either NSNumber, NSString, NSArray, NSDictionary or NSNull at the discretion of Foundation, I think.

Doing JSONSerialization.data(withJSONObject:) followed by JSONSerialization.jsonObject(with:) is not idempotent. That is, the value that you get back from the roundtrip is not guaranteed to be identical, since there is loss of information when Foundation needs to decide whether a Number should be treated as Double or Int (or really an NSNumber instance wrapping one of those types).

But when using Decodable there is no ambiguity since you declare your type in your decodable models.

1 Like

Thank you for detailed explanation! :clap:

But when using Decodable there is no ambiguity since you declare your type in your decodable models.

If only. The server I work with likes to send an array of [String: Any] objects where the values can be Double, Int, String, or Internet Date. My code knows the type of the value for specific keys. So at the Decodable level the values are all Any but in other places in the app the code is expecting an explicit type. So I have code that tries to decode to each of the known types. That's what this question reminded me of.

That sounds more appropriate for a JSON object than a JSON array. If they really decide to use an array, well, that's more boilerplate for the decoding process I guess :grimacing:.

Terms of Service

Privacy Policy

Cookie Policy