我正在使用Xcode 7 beta,并且迁移到Swift 2后,我在这行代码中遇到了一些问题:
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
我收到一个错误消息:“可以抛出调用,但是不能从全局变量初始化程序中抛出错误”。我的应用程序依赖recorder
作为全局变量。有没有办法使它保持全球性,但可以解决这些问题?我不需要高级错误处理,我只希望它能工作。
try!
来调用throwing函数以禁用错误传播。请注意,如果实际抛出错误,这将引发运行时异常。let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
Source: Apple Error Handling documentation (Disabling Error Propagation)
正在尝试?
// 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)")
}