【问题标题】:Swift: Cast Any Object to Int64 = nilSwift:将任何对象转换为 Int64 = nil
【发布时间】:2016-04-22 06:51:09
【问题描述】:

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

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 :)
}

【问题讨论】:

  • 可以是一篇不错的文章link
  • 谢谢,这让事情更清楚了

标签: swift int64


【解决方案1】:

let dict : [String : AnyObject] = ["intValue": 1234, "stringValue" : "some text"]

数字1234 存储为NSNumber 对象,并且可以 被转换为IntUIntFloat、...,但不是固定的 大小整数类型,如Int64

要在 32 位平台上检索 64 位值,您必须 明确地通过NSNumber

if let val = dict["intValue"] as? NSNumber {
    let int64value = val.longLongValue // This is an `Int64`
    print(int64value)
}

【讨论】:

    【解决方案2】:

    您现在可以直接使用 val.int64value 而不是 val.longLongValue,前提是 val 是 NSNumber

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 2015-08-03
      • 2014-10-23
      • 1970-01-01
      相关资源
      最近更新 更多