我有一个问题。我想知道为什么会这样?
var dict : [String : Any] = ["intValue": 1234, "stringValue" : "some text"]
dict["intValue"] as? Int64 // = nil (why)
dict["intValue"] as? Int // = 1234
谁能告诉我为什么转换为 Int64 会返回 nil?
编辑部分:
我已经简化了我的问题,但我认为这不是一个好主意。 :)
在我的特殊情况下,我将从 WKScriptMessage 的消息体。
我知道在 Dictionary 的一个字段中有一个 Int 值可以是 大于 Int32。
因此,如果我将此值转换为 Int,它将适用于 64 位系统。但是什么 发生在 32 位系统上?我认为这里是整数溢出还是?
我必须同时选中两者才能支持这两个系统吗?像这样:
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
。
要在 32 位平台上检索 64 位值,您必须
明确地通过 NSNumber
:
if let val = dict["intValue"] as? NSNumber {
let int64value = val.longLongValue // This is an `Int64`
print(int64value)
}
关于Swift:将任何对象转换为 Int64 = nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786883/