Swift: Cast Any Object to Int64 = nil

倖福魔咒の 提交于 2019-12-01 17:16:33

问题


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?

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.

I know that in one field of the Dictionary there is a Int value that can be greater than 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?

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

回答1:


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.

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



回答2:


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



来源:https://stackoverflow.com/questions/36786883/swift-cast-any-object-to-int64-nil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!