[英]Int64 does't work while Int works
I'm receiving a JSON and I want to parse it to get a value. 我收到一个JSON,我想解析它以获得一个值。 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
这是我的JSON
"location":"location here location","restaurantId":0
The print statement works just fine, but I get an exception on oneJson["restaurantId"] as! Int64
print语句工作正常,但我在
oneJson["restaurantId"] as! Int64
上得到一个例外oneJson["restaurantId"] as! Int64
oneJson["restaurantId"] as! Int64
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.
所以事实证明,当你得到一个AnyObject类型的字典时,Ints,Doubles,Floats,不会存储为Swift本机类型。 They're stored as... surprise!
他们被存储为......惊喜! NSNumber.
的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). 这会导致一系列不直观的行为,例如类型检查AnyObjects以查看您是否有Double或Int(无法完成)。
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. 并且一次又一次地提醒自己,当它是你正在投射的AnyObject时,Swift正在向你隐瞒它从NSNumber转换为Swift基类型的事实,事实上,它们仍然只是NSNumbers。
I would recommend, not to use Int64
(or Int32
). 我建议,不要使用
Int64
(或Int32
)。 Int
will be working in most cases. Int
将在大多数情况下工作。
See this post about the different integers in Swift: https://stackoverflow.com/a/27440158/4687348 查看有关Swift中不同整数的这篇文章: https : //stackoverflow.com/a/27440158/4687348
Yes, it's a known bug in Swift 3, which has been solved in Swift 4. 是的,它是Swift 3中的已知错误,已在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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.