Swift:将任何对象强制转换为Int64 = nil [英] Swift: Cast Any Object to Int64 = nil

查看:427
本文介绍了Swift:将任何对象强制转换为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对象,并且可以 强制转换为IntUIntFloat,...,但固定 像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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆