Swift AnyObject不能转换为String/Int

pJe*_*es2 34 swift xcode6-beta6

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

0x106bf1d07:  leaq   0x33130(%rip), %rax       ; "Swift dynamic cast failure"
Run Code Online (Sandbox Code Playgroud)

使用时例如:

self.id = reminderJSON["id"] as Int
Run Code Online (Sandbox Code Playgroud)

我有ResponseParser类及其内部(responseReminders是一个AnyObjects数组,来自AFNetworking responseObject):

for reminder in responseReminders {
    let newReminder = Reminder(reminderJSON: reminder)
        ...
}
Run Code Online (Sandbox Code Playgroud)

然后在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
}
Run Code Online (Sandbox Code Playgroud)

println(reminderJSON["id"]) 结果是:可选(3065522)

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

//编辑

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

if let id: AnyObject = reminderJSON["id"] { 
    self.id = Int(id as NSNumber) 
} 
Run Code Online (Sandbox Code Playgroud)

对于Int和

if let tempReceiver: AnyObject = reminderJSON["send_reminder_to"] { 
    self.id = "\(tempReceiver)" 
} 
Run Code Online (Sandbox Code Playgroud)

对于字符串

vac*_*ama 40

在斯威夫特,StringInt不是对象.这就是您收到错误消息的原因.你需要转换为NSStringNSNumber它们的对象.一旦你有了这些,它们可以分配给类型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
}
Run Code Online (Sandbox Code Playgroud)

  • String是一个结构.在Swift中,结构体可以有方法.不同之处在于它们的传递方式:结构通过值传递(复制),类通过引用(指针)传递.为了增加混乱,大多数情况下,Strings和NSStrings会自动桥接,因此您通常不必考虑它.你可以将一个Swift字符串传递给一个带有NSString的cocoa方法,它只是起作用.此演示实例是出现差异的情况之一. (6认同)

Gab*_*lla 5

reminderJSON["id"]给你一个AnyObject?,所以你不能把它投到Int你必须先解开它.

self.id = reminderJSON["id"]! as Int
Run Code Online (Sandbox Code Playgroud)

如果你确定id它将出现在JSON中.

if id: AnyObject = reminderJSON["id"] {
    self.id = id as Int
}
Run Code Online (Sandbox Code Playgroud)

除此以外