Int64 not working while Int is working

I get JSON and I want to parse it to get the value. I'm doing it

let ddd = oneJson["restaurantId"] as! Int print("ddd = \(ddd)") let restaurantId = oneJson["restaurantId"] as! Int64 

as you can see, I am parsing the same field. Here is my json

 "location":"location here location","restaurantId":0 

The print statement works fine, but I get an exception on oneJson["restaurantId"] as! Int64 oneJson["restaurantId"] as! Int64

enter image description here

+6
source share
3 answers

I like this quirk in quick (NOT).

This is one of the least intuitive mistakes in the language that I know of. Thus, it turns out that when you get a dictionary with the type AnyObject, Ints, Doubles, Floats, it is NOT stored as native Swift types. They are stored as ... a surprise! NSNumber.

This leads to a whole host of non-intuitive behaviors, for example to check the types of AnyObjects to see if you have Double or Int (this is not possible).

For the same reason, your code does not work. Change it to:

 let ddd = oneJson["restaurantId"] as! Int print("ddd = \(ddd)") let restaurantId = (oneJson["restaurantId"] as? NSNumber)?.longLongValue 

And again and again remind yourself that when you make AnyObject, Swift hides from you the fact that it throws from NSNumber for Swift's basic types, and in fact they are still just NSNumbers.

+7
source

I would recommend not using Int64 (or Int32 ). Int will work in most cases.

See this post about different integers in Swift: fooobar.com/questions/239525 / ...

0
source

Yes, this is a known bug in Swift 3 that was resolved in Swift 4.
Now you just write like this:

 let n = NSNumber.init(value: 9223372036854775807) // 2^63 - 1 print(n, n as! Int64) // will print the right answer. 
0
source

All Articles