我试图从我的商店获取数据,但收到以下错误:
'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]
}
答案 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
。