我想将JSON解析为对象,但我不知道如何将AnyObject强制转换为String或Int,因为我得到的是:
0x106bf1d07: leaq 0x33130(%rip), %rax ; "Swift dynamic cast failure"
使用例如:
self.id = reminderJSON["id"] as Int
我有一个ResponseParser类,里面有一个responseReminders属性,它是AnyObjects的数组,来自于AFNetworking的responseObject:
for reminder in responseReminders {
let newReminder = Reminder(reminderJSON: reminder)
...
}
然后在Reminder类中,我像这样初始化它(提醒作为AnyObject,但是是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"])
的结果是:Optional(3065522)
在这种情况下,我该如何将AnyObject向下转换为String或Int?
//编辑
尝试了一些方法后,我得出了以下解决方案:
if let id: AnyObject = reminderJSON["id"] {
self.id = Int(id as NSNumber)
}
对于整数和
if let tempReceiver: AnyObject = reminderJSON["send_reminder_to"] {
self.id = "\(tempReceiver)"
}
字符串相关操作
reminderJSON["id"] as Int?
- Antonioas
已经变成了as!
。 - LinusGeffarth