Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an error pointer in the Swift language?

Tags:

swift

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)") } 
like image 874
AperioOculus Avatar asked Jun 06 '14 14:06

AperioOculus


People also ask

How to pass error in Swift?

There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a do - catch statement, handle the error as an optional value, or assert that the error will not occur.

Does Swift have exceptions?

Swift doesn't support throwing exceptions, nor does it support catching them. This wouldn't be a problem if you could develop iOS apps in pure Swift, but unfortunately at the moment you cannot.

What is NSError in Swift?

Information about an error condition including a domain, a domain-specific error code, and application-specific information.

Which keyword is useful to stop error propagation in Swift language a try?

Swift Disabling an Error Propagation In those cases, we can use try! before an expression to disable error propagation. During execution, if no error occurred then try! will return the value in case if any error occurred, we will get a runtime error. Following is the example of disabling an error propagation using try!


2 Answers

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

like image 131
Jiaaro Avatar answered Sep 23 '22 13:09

Jiaaro


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 } 
like image 39
pxpgraphics Avatar answered Sep 20 '22 13:09

pxpgraphics