调用可以抛出,但不能抛出全局变量初始值设定项之外的错误
Call can throw, but errors can not be thrown out of a global variable initializer
我正在使用 Xcode 7 beta,在迁移到 Swift 2 之后,我遇到了这行代码的一些问题:
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
我收到一条错误消息 "Call can throw, but errors can not be thrown out of a global variable initializer"。
我的应用依赖 recorder
作为全局变量。有没有办法让它保持全局但解决这些问题?我不需要高级错误处理,我只希望它能正常工作。
您可以使用 3 种方法来解决这个问题。
- 正在使用 try 创建可选的 AVAudioRecorder?
- 如果你知道它会return你的AVRecorder,你可以隐式使用try!
- 或者使用 try / catch 处理错误
使用试试?
// 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)")
}
如果您知道您的函数调用不会抛出异常,您可以使用 try!
调用抛出函数来禁用错误传播。请注意,如果实际抛出错误,这将抛出运行时异常。
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
Source: Apple Error Handling documentation (Disabling Error Propagation)
我正在使用 Xcode 7 beta,在迁移到 Swift 2 之后,我遇到了这行代码的一些问题:
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
我收到一条错误消息 "Call can throw, but errors can not be thrown out of a global variable initializer"。
我的应用依赖 recorder
作为全局变量。有没有办法让它保持全局但解决这些问题?我不需要高级错误处理,我只希望它能正常工作。
您可以使用 3 种方法来解决这个问题。
- 正在使用 try 创建可选的 AVAudioRecorder?
- 如果你知道它会return你的AVRecorder,你可以隐式使用try!
- 或者使用 try / catch 处理错误
使用试试?
// 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)")
}
如果您知道您的函数调用不会抛出异常,您可以使用 try!
调用抛出函数来禁用错误传播。请注意,如果实际抛出错误,这将抛出运行时异常。
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
Source: Apple Error Handling documentation (Disabling Error Propagation)