Jon Brooks
Jon Brooks

Reputation: 2492

Swift 2: Catching errors in a closure

I've got the following code, which uses a closure to lazily initialize a property:

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

}()

The code as written produces the error:

Call can throw, but it is not marked with 'try' and the error is not handled

The code is marked with 'try' and the error is handled. When I move the closure into a separate function and call it here, everything works as expected.

Is there something about closures and do/try/catch that I don't understand, or have I encountered (yet another!) bug in the wonderful Swift 2 compiler?

Upvotes: 1

Views: 483

Answers (1)

Mario Zannone
Mario Zannone

Reputation: 2883

The problem is that your catch does not catch all the possible exceptions, so the closure can still throw. Use a generic 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
}()

Upvotes: 2

Related Questions