我有以下代码,它使用闭包延迟初始化属性:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try coordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
} catch let err as NSError {
XCTFail("error creating store: \(err)")
}
return coordinator
}()
编写的代码产生错误:
Call can throw, but it is not marked with 'try' and the error is not handled
代码标有'try',错误被处理。当我将闭包移动到一个单独的函数中并在此处调用它时,一切都按预期进行。
关于闭包和 do/try/catch 有什么我不明白的,或者我遇到过(又一个!)美妙的 Swift 2 编译器中的错误?
最佳答案
问题是你的 catch 没有捕获所有可能的异常,所以闭包仍然可以抛出。使用通用捕获:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try coordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
} catch {
XCTFail("error creating store: \(error)")
}
return coordinator
}()
关于 swift 2 : Catching errors in a closure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469053/