Open Search

Do try and catch my errors in Swift 2

November 10, 2015 11:26 am
Categorised in:
Reading Time: 1

This is bugging me, I keep forgetting it, I’m noting it down.

Swift 2 has changed error handling, just as I was wrapping my head around error handling in Swift 1. Typicals.

The easiest thing to do is wherever you see a method which ends with error e.g.:

audioRecorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as [NSObject : AnyObject], error: &error)

This will kick in an error from the debugger. Bugger. Solve it by wrapping the method in a do block and catch the error after the block so the above becomes:

do{
audioRecorder = try AVAudioRecorder(URL: soundFileURL, settings: recordSettings as [NSObject : AnyObject])
} catch let error as NSError {
  print("Error: \(error.domain)")
}

This StackOverflow answer set me straight on my errors with error handling and allowed me to retain a greater amount of my hair in the process . As always, praise be to the digital gods for StackOverflow.

This joint was penned by @elmarko