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

后端 未结 2 1224
再見小時候
再見小時候 2021-02-13 19:59

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, settin         


        
2条回答
  •  感情败类
    2021-02-13 20:47

    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)")
    }
    

提交回复
热议问题