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

时间:2021-10-18 12:10:20

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

can anybody tell me why the cast to Int64 returns nil?

任何人都可以告诉我为什么Int64的强制转换为零?

Edited part:

I have simplify my question, but i think this was not a good idea. :)

我简化了我的问题,但我认为这不是一个好主意。 :)

In my special case I will get back a Dictionary from a message body of WKScriptMessage.

在我的特殊情况下,我将从WKScriptMessage的消息体中获取一个Dictionary。

I know that in one field of the Dictionary there is a Int value that can be greater than Int32.

我知道在Dictionary的一个字段中有一个Int值可以大于Int32。

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?

因此,如果我将此值转换为Int,它将适用于64位系统。但是在32位系统上发生了什么?我想这里是整数溢出还是?

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

2 个解决方案

#1


9  

In

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

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.

数字1234存储为NSNumber对象,可以转换为Int,UInt,Float,...,但不能转换为固定大小的整数类型,如Int64。

To retrieve a 64-bit value even on 32-bit platforms, you have to go via NSNumber explicitly:

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

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

#2


0  

You can now directly use val.int64value instead of val.longLongValue, provided val is a NSNumber

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

#1


9  

In

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

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.

数字1234存储为NSNumber对象,可以转换为Int,UInt,Float,...,但不能转换为固定大小的整数类型,如Int64。

To retrieve a 64-bit value even on 32-bit platforms, you have to go via NSNumber explicitly:

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

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

#2


0  

You can now directly use val.int64value instead of val.longLongValue, provided val is a NSNumber

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