7

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

Jojodmo
  • 23,357
  • 13
  • 65
  • 107
sarah
  • 1,201
  • 1
  • 9
  • 29
  • I don't know what's causing this problem (hence the comment), but try using `(oneJson["restaurantId"] as! NSString).longLongValue`, which will give a value with the type `Int64` – Jojodmo Jan 19 '16 at 00:39

3 Answers3

8

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.

tbondwilkinson
  • 1,067
  • 2
  • 8
  • 16
  • As an aside, you're going to have to trust your JSON library to know to read it's input properly as an int 64, or else you might be losing precision. I've never tested this, and haven't seen your implementation details, but it's worth testing for sure. – tbondwilkinson Jan 19 '16 at 00:48
0

I would recommend, not to use Int64 (or Int32). Int will be working in most cases.

See this post about the different integers in Swift: https://stackoverflow.com/a/27440158/4687348

Community
  • 1
  • 1
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
  • sorry but this is not an answer, i'm asking for Int64, and I know why I need Int64 not just Int. – sarah Jan 19 '16 at 00:41
  • This may be good advice, but it doesn't actually solve the problem of turning the value into an `Int64` – Jojodmo Jan 19 '16 at 00:41
  • I think it would be better to use `String`, instead of `Int` or `Int64`, just because javascript is not friendly with Int64, which will be truncated in `js`. – DawnSong Sep 20 '17 at 02:06
0

Yes, it's a known bug in Swift 3, which has been solved 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.
DawnSong
  • 4,752
  • 2
  • 38
  • 38