我想解析一个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”])result is:可选(3065522)
我怎么可以downcast AnyObject到String或Int在这样的情况下?
//编辑
经过一些尝试,我来与这个解决方案:
if let id: AnyObject = reminderJSON["id"] { self.id = Int(id as NSNumber) }
为Int和
if let tempReceiver: AnyObject = reminderJSON["send_reminder_to"] { self.id = "\(tempReceiver)" }
为字符串
在Swift中,String和Int不是对象。这就是为什么你得到错误消息。你需要转换为NSString和NSNumber,它们是对象。一旦你有这些,它们可以分配给类型String和Int的变量。
原文链接:https://www.f2er.com/swift/321041.html我推荐以下语法:
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 }