Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call can throw, but errors can not be thrown out of a global variable initializer

Tags:

swift

swift2

I'm using Xcode 7 beta and after migrating to Swift 2 I experienced some issues with this line of code:

let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])

I get an error saying "Call can throw, but errors can not be thrown out of a global variable initializer". My app relies on the recorder to be a global variable. Is there a way to keep it global but fix these issues? I have no need for advanced error handling, I just want it to work.

like image 850
ecoguy Avatar asked Jun 11 '15 09:06

ecoguy


2 Answers

If you know that your function call will not throw an exception, you can call the throwing function with try! to disable error propagation. Note that this will throw a runtime exception if an error is actually thrown.

let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])

Source: Apple Error Handling documentation (Disabling Error Propagation)

like image 186
blau Avatar answered Oct 05 '22 03:10

blau


There are 3 ways that you can use to solve this problem.

  • Creating optional AVAudioRecorder using try?
  • If you know that it will return you AVRecorder, you can implicity use try!
  • Or then handle the error using try / catch

Using try?

// notice that it returns AVAudioRecorder?
if let recorder = try? AVAudioRecorder(URL: soundFileURL, settings: recordSettings) { 
    // your code here to use the recorder
}

Using try!

// this is implicitly unwrapped and can crash if there is problem with soundFileURL or recordSettings
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings)

try / catch

// The best way to do is to handle the error gracefully using try / catch
do {
    let recorder = try AVAudioRecorder(URL: soundFileURL, settings: recordSettings)
} catch {
    print("Error occurred \(error)")
}
like image 31
Sandeep Avatar answered Oct 05 '22 03:10

Sandeep