【发布时间】:2014-10-16 10:18:36
【问题描述】:
我想将 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"]) 结果为:可选(3065522)
在这种情况下,如何将 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)"
}
对于字符串
【问题讨论】:
-
您是否尝试过强制转换为可选项?
reminderJSON["id"] as Int? -
您应该将您的解决方案添加到您的问题中作为答案,而不是编辑您的问题。我们允许/鼓励您在 StackOverflow 上回答自己的问题。
-
我对字符串使用了相同的解决方案,比类型转换和测试要容易得多!
-
谢谢,但自 Swift 1.2 起,
as就是as!。
标签: swift xcode6-beta6