How to pass an error pointer in the Swift language?

Swift

Swift Problem Overview


I am attempting to pass an error pointer in swift and am unable to do so. The compiler complains that "NSError is not convertible to 'NSErrorPointer'".

var error: NSError = NSError()
var results = context.executeFetchRequest(request, error: error)
		
if(error != nil)
{
	println("Error executing request for entity \(entity)")
}

Swift Solutions


Solution 1 - Swift

You just pass a reference like so:

var error: NSError?
var results = context.executeFetchRequest(request, error: &error)

if error != nil {
    println("Error executing request for entity \(entity)")
}

Two important points here:

  1. NSError? is an optional (and initialized to nil)
  2. you pass by reference using the & operator (e.g., &error)

See: Using swift with cocoa and objective-c

Solution 2 - Swift

This suggestion is up for discussion, but some engineers would prefer to use the golden path syntax:

var maybeError: NSError?
if let results = context.executeFetchRequest(request, error: &maybeError) {
 	// Work with results
} else if let error = maybeError {
	// Handle the error
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAperioOculusView Question on Stackoverflow
Solution 1 - SwiftJiaaroView Answer on Stackoverflow
Solution 2 - SwiftpxpgraphicsView Answer on Stackoverflow