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
在斯威夫特,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
}
Run Code Online (Sandbox Code Playgroud)
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)
除此以外
| 归档时间: |
|
| 查看次数: |
60233 次 |
| 最近记录: |