Swift AnyObject is not convertible to String/Int

pJes2 picture pJes2 · Aug 22, 2014 · Viewed 61.1k times · Source

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

Answer

vacawama picture vacawama · Sep 1, 2014

In Swift, String and Int are not objects. This is why you are getting the error message. You need to cast to NSString and NSNumber which are objects. Once you have these, they are assignable to variables of the type String and Int.

I recommend the following syntax:

if let id = reminderJSON["id"] as? NSNumber {
    // If we get here, we know "id" exists in the dictionary, and we know that we
    // got the type right. 
    self.id = id 
}

if let receiver = reminderJSON["send_reminder_to"] as? NSString {
    // If we get here, we know "send_reminder_to" exists in the dictionary, and we
    // know we got the type right.
    self.receiver = receiver
}