dschmidt dschmidt - 2 years ago 191
Swift Question

Swift: Cast Any Object to 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

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

Answer Source


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`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download