Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int64 does't work while Int works

Tags:

json

ios

swift

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

enter image description here

like image 325
sarah Avatar asked Jan 19 '16 00:01

sarah


People also ask

What is the difference between Int32 and int64 in Swift?

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.

How big is int64 in Golang?

A variable of type int64 can store integers ranging from -9223372036854775808 til **9223372036854775807.

What is int64 in Swift?

A 64-bit signed integer value type.

What is int64 in Golang?

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.


1 Answers

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.

like image 136
tbondwilkinson Avatar answered Oct 07 '22 12:10

tbondwilkinson