Swift AnyObject不能转换为String/Int

编程入门 行业动态 更新时间:2024-10-28 20:26:27
本文介绍了Swift AnyObject不能转换为String/Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想解析一个JSON到对象,但是我不知道如何将AnyObject转换为String或Int,因为我得到了:

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"

在使用示例时:

self.id = reminderJSON["id"] as Int

我有ResponseParser类,并且在其内部(responseReminders是AFNetworking responseObject的AnyObjects数组):

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) ... }

然后在Reminder类中将其初始化(提醒为AnyObject,但它是Dictionary(String,AnyObject)):

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"])结果是:可选(3065522)

println(reminderJSON["id"]) result is: Optional(3065522)

在这种情况下,如何将AnyObject转换为String或Int?

How can I downcast AnyObject to String or Int in case like this?

//编辑

经过一番尝试,我提出了以下解决方案:

After some tries I come with this solution:

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的变量.

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.

我建议使用以下语法:

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 }

更多推荐

Swift AnyObject不能转换为String/Int

本文发布于:2023-11-12 18:07:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582172.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   AnyObject   Swift   String   Int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!