Swift AnyObject不能转换为String/Int

我想解析一个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
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...