Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON AnyObject to Int64

Tags:

swift

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

Is there a way to typeCast a AnyObject to Int64? I am receiving a huge number via JSON this number arrives at my class as "AnyObject" - how can I cast it to Int64 - xcode just says its not possible.

like image 848
dburgmann Avatar asked Sep 22 '14 12:09

dburgmann


2 Answers

JSON numbers 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 don't know that this conversion will be successful.

like image 87
Rob Napier Avatar answered Sep 20 '22 16:09

Rob Napier


You can cast from a AnyObject to an Int with the as type cast operator, but to downcast into different numeric types you need to use the target type's initializer.

var o:AnyObject = 1
var n:Int = o as Int
var u:Int64 = Int64(n)
like image 39
Ramesh Avatar answered Sep 16 '22 16:09

Ramesh