来自AnyObject的Swift类型转换

时间:2014-10-02 08:09:18

标签: ios swift casting

我试图从我的商店获取数据,但收到以下错误:

'Event' is not identical to 'AnyObject'

我有一个events变量,这是一个Event数组。我想从获取请求返回的数据来自类型AnyObject。因此我尝试将其强制转换为[Event],但它不起作用,我无法弄清楚原因。

var events: [Event] = []

func loadDataFromDB() {
  let fetchRequest = NSFetchRequest(entityName: "Event")
  events = context?.executeFetchRequest(fetchRequest, error: nil) as [Event]
}

1 个答案:

答案 0 :(得分:0)

当涉及可选链接时,似乎会出现某种错误。使用这些替代方法解决方法:

events = context?.executeFetchRequest(fetchRequest, error: nil) as [AnyObject]? as [Event]
events = (context?.executeFetchRequest(fetchRequest, error: nil))! as [Event]
events = context!.executeFetchRequest(fetchRequest, error: nil) as [Event]

为了安全起见,我建议使用:

if let result = context?.executeFetchRequest(fetchRequest, error: nil) {
    events = result as [Event]
}

如果有executeFetchRequest,则返回nil