Swift:将任何对象强制转换为Int64 = nil [英] Swift: Cast Any Object to Int64 = nil
问题描述
我有一个问题.我想知道为什么会这样吗?
i have a question. I was wondering why this is happend?
var dict : [String : Any] = ["intValue": 1234, "stringValue" : "some text"]
dict["intValue"] as? Int64 // = nil (why)
dict["intValue"] as? Int // = 1234
有人可以告诉我为什么对Int64进行强制转换会返回nil吗?
can anybody tell me why the cast to Int64 returns nil?
已编辑部分:
我已经简化了我的问题,但是我认为这不是一个好主意. :)
I have simplify my question, but i think this was not a good idea. :)
在特殊情况下,我会从 WKScriptMessage的消息正文.
In my special case I will get back a Dictionary from a message body of WKScriptMessage.
我知道在词典的一个字段中有一个Int值,可以是 大于Int32.
I know that in one field of the Dictionary there is a Int value that can be greater than Int32.
因此,如果我将此值转换为Int,它将在64位系统上运行.但是呢 发生在32位系统上?我认为这是整数溢出还是?
So if I cast this value to Int it will works on 64-bit systems. But what happend on 32-bit systems? I think here is a integer overflow or?
我必须同时选中两者才能支持这两个系统吗?像这样:
Must I check both to support both systems? Something like this:
func handleData(dict: [String : AnyObject]) {
val value: Int64?
if let int64Value = dict["intValue"] as? Int64 {
value = int64Value
} else if let intValue = dict["intValue"] as? Int {
value = intValue
}
//do what ever i want with the value :)
}
推荐答案
在
let dict : [String : AnyObject] = ["intValue": 1234, "stringValue" : "some text"]
数字1234
被存储为NSNumber
对象,并且可以
强制转换为Int
,UInt
,Float
,...,但不固定
像Int64
这样的整数类型.
the number 1234
is stored as an NSNumber
object, and that can
be cast to Int
, UInt
, Float
, ..., but not to the fixed
size integer types like Int64
.
要即使在32位平台上也要检索64位值,您必须
明确地通过NSNumber
进行操作:
To retrieve a 64-bit value even on 32-bit platforms, you have to
go via NSNumber
explicitly:
if let val = dict["intValue"] as? NSNumber {
let int64value = val.longLongValue // This is an `Int64`
print(int64value)
}
这篇关于Swift:将任何对象强制转换为Int64 = nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!