我想解析一个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的变量。
我推荐以下语法:
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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。