Swift AnyObject不能转换为String / Int

时间:2014-08-22 14:14:28

标签: swift xcode6-beta6

我想将JSON解析为object,但我不知道如何将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"])结果为:可选(3065522)

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

// EDIT

经过一些尝试,我得到了这个解决方案:

if let id: AnyObject = reminderJSON["id"] { 
    self.id = Int(id as NSNumber) 
} 

表示Int和

if let tempReceiver: AnyObject = reminderJSON["send_reminder_to"] { 
    self.id = "\(tempReceiver)" 
} 

表示字符串

4 个答案:

答案 0 :(得分:40)

在Swift中,StringInt不是对象。这就是您收到错误消息的原因。您需要转换为对象NSStringNSNumber。获得这些内容后,可以将其分配给StringInt类型的变量。

我建议使用以下语法:

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
}

答案 1 :(得分:5)

reminderJSON["id"]会为您提供AnyObject?,因此您无法将其投放到Int您必须先解开它。

待办事项

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

如果您确定JSON中会出现id

if id: AnyObject = reminderJSON["id"] {
    self.id = id as Int
}

,否则

答案 2 :(得分:2)

现在你需要import foundation。 Swift会将值type(String,int)转换为对象types(NSString,NSNumber)。由于AnyObject适用于所有对象,因此编译器不会投诉。

答案 3 :(得分:1)

这实际上非常简单,可以在一行中提取,投放和解包值:if let s = d["2"] as? String,如:

var d:[String:AnyObject] = [String:AnyObject]()
d["s"] = NSString(string: "string")

if let s = d["s"] as? String {
    println("Converted NSString to native Swift type")
}
相关问题