Swift AnyObject不能转换为String / Int
我想分析一个JSON对象,但我不知道如何将AnyObject转换为String或Int,因为我得到:
0x106bf1d07: leaq 0x33130(%rip), %rax ; "Swift dynamic cast failure" 当使用例如:
 self.id = reminderJSON["id"] as Int 
我有ResponseParser类和它里面(responseReminders是从AFNetworking responseObject的AnyObject的数组):
 for reminder in responseReminders { let newReminder = Reminder(reminderJSON: 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) } 
为国际和
 if let tempReceiver: AnyObject = reminderJSON["send_reminder_to"] { self.id = "\(tempReceiver)" } 
为string
 在Swift中, String和Int不是对象。 这就是为什么你收到错误信息。 你需要转换为NSString和NSNumber这些对象。 一旦你有了这些,它们可以分配给String和Inttypes的variables。 
我推荐以下语法:
 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 } 
  reminderJSON["id"]给你一个AnyObject?  ,所以你不能把它强制转换成Int你必须首先打开它。 
做
 self.id = reminderJSON["id"]! as Int 
 如果你确定这个id将出现在JSON中。 
 if id: AnyObject = reminderJSON["id"] { self.id = id as Int } 
除此以外
 现在你只需要import foundation 。  Swift会将值type(String,int)转换为对象types(NSString,NSNumber) 。由于AnyObject支持所有对象,因此编译器不会投诉。 
 这实际上很简单,值可以提取,铸造和解包在一行: if let s = d["2"] as? String  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") }