Swift:将任何对象转换为 Int64 = nil

标签 swift int64

我有一个问题。我想知道为什么会这样?

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/

相关文章:

swift - UITest比较期望中元素的值

ios - 尝试将可选的 Int64 分配给字典键时,类型 'Int64' 和 '_' 不匹配

c++ - 64 位整数和旧的 C++ 编译器

types - 为什么我的类型构造函数没有被识别

ios - 将 String 转换为 Int64 导致 32 位设备崩溃

ios - 确认 Action 的模式框 swift 完成

ios - 视频并不总是导出到相机胶卷 : NSFileManager's removeItemAtPath non-blocking?

uitableview - fetchedResultsController核心数据 fatal error : unexpectedly found nil while unwrapping an Optional value

swift - 停止 SKPhysicsBody 运动中

testing - 如何测试无符号 __int64 数字是否超出范围