Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-01-19

NSError

2015-09-18: See my follow up post for the Swift 2.0 changes.

Sooner or later every developer will need to use an API with an NSErrorPointer in it.

For example when reading a file:

String(contentsOfFile: String,
       encoding: NSStringEncoding,
       error: NSErrorPointer)

It's not difficult to use, but if you are like me, the first time I raised my eyebrows, I was not expecting to use pointers in Swift. How do we do that?

Like most stuff, its really simple, once you know how:

var error: NSError?
let content = String(contentsOfFile: myPath,
                     encoding: NSUTF8StringEncoding,
                     error: &error)

It is important to define 'error' as a 'var', turns out that we cannot use pointers for variables created with 'let'. Even when you never intent to change the value. Also, do not assign a value to 'error', though you can assign 'nil' if you like (but the compiler will do it for you).

The API call will create an error for us if it needs to. After the API call, the 'error' will be non-nil if an error occurred.

For evaluation we use the error var as follows:

   // Read the file into a string
        
   var error: NSError?

   let content = String(contentsOfFile: path,
                        encoding: NSUTF8StringEncoding,
                        error: &error)

   if let message = error?.localizedDescription {
      println(message)
      return nil
   }

   return content

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment