I want to parse a JSON to object, but I have no idea how to cast AnyObject to String or Int since I'm getting:
0x106bf1d07: leaq 0x33130(%rip), %rax ; "Swift dynamic cast failure"
When using for example:
self.id = reminderJSON["id"] as Int
I have ResponseParser class and inside of it (responseReminders is an Array of AnyObjects, from AFNetworking responseObject):
for reminder in responseReminders {
let newReminder = Reminder(reminderJSON: reminder)
...
}
Then in Reminder class I'm initialising it like this (reminder as AnyObject, but is Dictionary(String, AnyObject)):
var id: Int
var receiver: String
init(reminderJSON: AnyObject) {
self.id = reminderJSON["id"] as Int
self.receiver = reminderJSON["send_reminder_to"] as String
}
println(reminderJSON["id"])
result is: Optional(3065522)
How can I downcast AnyObject to String or Int in case like this?
//EDIT
After some tries I come with this solution:
if let id: AnyObject = reminderJSON["id"] {
self.id = Int(id as NSNumber)
}
for Int and
if let tempReceiver: AnyObject = reminderJSON["send_reminder_to"] {
self.id = "\(tempReceiver)"
}
for string
Now you just need to
import foundation
. Swift will convert valuetype(String,int)
into objecttypes(NSString,NSNumber)
.Since AnyObject works with all objects now compiler will not complaint.reminderJSON["id"]
gives you anAnyObject?
, so you cannot cast it toInt
You have to unwrap it first.Do
if you're sure that
id
will be present in the JSON.otherwise
This is actually pretty simple, the value can be extracted, casted, and unwrapped in one line:
if let s = d["2"] as? String
, as in:In Swift,
String
andInt
are not objects. This is why you are getting the error message. You need to cast toNSString
andNSNumber
which are objects. Once you have these, they are assignable to variables of the typeString
andInt
.I recommend the following syntax: