我有一些这样的功能:
func getAllEntities() -> [MyEntity]? {
let fetchRequest = NSFetchRequest(entityName:"MyEntity")
var error: NSError?
let fetchedResults = context.executeFetchRequest(fetchRequest) as! [MyEntity]?
if let results = fetchedResults {
return results
}
else {
print("Could not fetch \(error), \(error!.userInfo)")
}
}
return nil
}
现在升级到 Swift 2
和 Xcode 7
,我收到如下错误:
Cannot downcast from '[AnyObject]' to a more optional type '[MyEntity]?'
Call can throw, but it is not marked with 'try' and the error is not handled
这是在您首次启动 Xcode 7
时执行自动 Swift
代码迁移后进行的操作。在新的 Swift 版本中重写函数的正确方法是什么?
谢谢
编辑:我需要保持与 iOS 7
和 iOS 8
的向后兼容性。
最佳答案
有两个错误:
- 在 Swift 2 中,
executeFetchRequest()
返回一个非可选值。因此您无法将返回值转换为[MyEntity]?
。您可以(强制或可选)将其转换为[MyEntity]
。 executeFetchRequest()
在错误情况下抛出错误,因此它必须 在do-catch
语句中使用try
进行调用。
示例:
func getAllEntities() -> [MyEntity]? {
let fetchRequest = NSFetchRequest(entityName: "MyEntity")
do {
let results = try context.executeFetchRequest(fetchRequest) as! [MyEntity]
return results
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return nil
}
}
强制转换为! [MyEntity]
在这里是可以接受的(就像你的
原始代码)因为您知道实体的类,它是
在核心数据模型检查器中设置。
关于ios - 将 Core Data 相关代码迁移到 Swift 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624216/