2015-06-11 42 views
9

我使用的Xcode 7測試版,並遷移到斯威夫特2後,我經歷了一些問題,這行代碼:呼叫可以拋出,但錯誤不能拋出一個全局變量初始化

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

我得到一個錯誤,說「調用可以拋出,但錯誤不能拋出全局變量初始值設定項」。 我的應用程序依靠recorder是一個全局變量。有沒有辦法讓它保持全球化,但解決這些問題?我不需要高級錯誤處理,我只是希望它能夠工作。

回答

7

有3種方法可以用來解決此問題。

  • 使用try創建可選的AVAudioRecorder?
  • 如果你知道它會返回你AVRecorder,你可以默示使用試試吧!
  • 或者然後使用try/catch語句

使用嘗試處理錯誤?

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

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