Swift AnyObject不能转换为String/Int

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中,StringInt不是对象.这就是为什么您收到错误消息的原因.您需要强制转换为对象的NSStringNSNumber.一旦拥有这些变量,它们就可以分配给类型为StringInt的变量.

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
}