I'm receiving a JSON and I want to parse it to get a value. I'm doing this
let ddd = oneJson["restaurantId"] as! Int
print("ddd = \(ddd)")
let restaurantId = oneJson["restaurantId"] as! Int64
as you see, I'm parsing the same field. Here's my JSON
"location":"location here location","restaurantId":0
The print statement works just fine, but I get an exception on oneJson["restaurantId"] as! Int64
In most cases, you don't need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform's native word size: On a 32-bit platform, Int is the same size as Int32. On a 64-bit platform, Int is the same size as Int64.
A variable of type int64 can store integers ranging from -9223372036854775808 til **9223372036854775807.
A 64-bit signed integer value type.
An int64 is the typical choice when memory isn't an issue. In particular, you can use a byte , which is an alias for uint8 , to be extra clear about your intent. Similarly, you can use a rune , which is an alias for int32 , to emphasize than an integer represents a code point.
I love this quirk in swift (NOT).
It's one of the least intuitive gotchas of the language I know of. So it turns out that when you get a Dictionary with type AnyObject, Ints, Doubles, Floats, ARE NOT stored as the Swift native types. They're stored as... surprise! NSNumber.
Which leads to a whole host of unintuitive behavior, for instance type checking AnyObjects to see whether you have a Double or an Int (it can't be done).
For the same reason, your code is failing. Change it to:
let ddd = oneJson["restaurantId"] as! Int
print("ddd = \(ddd)")
let restaurantId = (oneJson["restaurantId"] as? NSNumber)?.longLongValue
And remind yourself again and again that when it's an AnyObject you're casting from, Swift is hiding from you the fact that it does a cast from NSNumber to Swift base types, and that in truth, they're still just NSNumbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With