swift 2 : Catching errors in a closure

标签 swift closures try-catch

我有以下代码,它使用闭包延迟初始化属性:

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/

相关文章:

swift - 如何通过 FacebookUtil 链接现有的 Parse 用户

swift - Vapor Fluent 不会因违反外键约束而抛出

swift - 引用弱引用变量时是否应该用 'weak' 指定计算属性?

javascript - JS Closure - 依赖于回调的多个日期选择器初始化/调用

c++ - 使用 auto 返回不同的 Lambda

ios - 带有 completionHandler 的 block 的 Swift 语法...在委托(delegate)方法中

java - Try With Resources 与 Try-Catch

ios - iOS中如何通过CMMotionManager获取实际加速度

java - try catch会降低效率吗?

c# - 捕获/抛出堆栈跟踪丢失错误行号