Swift 2 ( executeFetchRequest ) : error handling

As of Swift 2, Cocoa methods that produce errors are translated to Swift functions that throw an error.

Instead of an optional return value and an error parameter as in Swift 1.x:

var error : NSError?
if let result = context.executeFetchRequest(request, error: &error) {
    // success ...
    list = result
} else {
    // failure
    println("Fetch failed: \(error!.localizedDescription)")
}

in Swift 2 the method now returns a non-optional and throws an error
in the error case, which must be handled with try-catch:

do {
    list = try context.executeFetchRequest(request)
    // success ...
} catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
}

For more information, see “Error Handling” in “Adopting Cocoa Design Patterns”
in the “Using Swift with Cocoa and Objective-C” documentation.

Leave a Comment