我正在使用Xcode 7 beta,在迁移到Swift 2后,我遇到了一些代码问题:
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
我收到错误说" Call可以抛出,但错误不能从全局变量初始化程序中抛出"。
我的应用程序依赖recorder
作为全局变量。有没有办法让它保持全球化,但解决这些问题?我不需要高级错误处理,我只是想让它工作。
答案 0 :(得分:17)
如果您知道函数调用不会引发异常,则可以使用try!
调用throw函数来禁用错误传播。请注意,如果实际抛出错误,这将抛出运行时异常。
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
Source: Apple Error Handling documentation (Disabling Error Propagation)
答案 1 :(得分:11)
您可以使用3种方法来解决此问题。
使用试用?
// notice that it returns AVAudioRecorder?
if let recorder = try? AVAudioRecorder(URL: soundFileURL, settings: recordSettings) {
// your code here to use the recorder
}
使用试试!
// this is implicitly unwrapped and can crash if there is problem with soundFileURL or recordSettings
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings)
尝试/抓住
// 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)")
}