Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Cast Any Object to Int64 = nil

Tags:

swift

int64

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 :)
}
like image 481
Daniel Schmidt Avatar asked Apr 22 '16 06:04

Daniel Schmidt


1 Answers

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)
}
like image 196
Martin R Avatar answered Oct 15 '22 04:10

Martin R