Convert JSON AnyObject to Int64

this is somewhat related to this question: How to properly store a timestamp (since 1970)

Is there a way to print an AnyObject for Int64? I get a huge amount through JSON, this number comes to my class as "AnyObject" - how can I pass it to Int64 - xcode just says that this is not possible.

+7
swift
source share
4 answers

The JSON digits are NSNumber , so you'll want to go through there.

 import Foundation var json:AnyObject = NSNumber(longLong: 1234567890123456789) var num = json as? NSNumber var result = num?.longLongValue 

Note that result is Int64? , since you do not know that this conversion will be successful.

+28
source share

You can cast from AnyObject to Int with a cast operator of type, but to reset to different numeric types, you need to use an initializer of the target type.

 var o:AnyObject = 1 var n:Int = o as Int var u:Int64 = Int64(n) 
+2
source share

Try SwiftJSON , which is the best way to work with JSON data in Swift

 let json = SwiftJSON.JSON(data: dataFromServer) if let number = json["number"].longLong { //do what you want } else { //print the error message if you like println(json["number"]) } 
+1
source share

As @Rob Napier's answer says, you are dealing with NSNumber . If you are sure that you have a valid one, you can do this to get Int64

 (json["key"] as! NSNumber).longLongValue 
+1
source share

All Articles