Swift AnyObject不能转换为String/Int
发布时间:2020-12-14 06:04:19 所属栏目:百科 来源:网络整理
导读:我想解析一个JSON对象,但我不知道如何将AnyObject转换为String或Int,因为我得到: 0x106bf1d07: leaq 0x33130(%rip),%rax ; "Swift dynamic cast failure" 当使用例如: self.id = reminderJSON["id"] as Int 我有ResponseParser类和它内部(responseRemind
我想解析一个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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |