我正在使用Xcode 7 beta,在迁移到Swift 2后,我遇到了一些代码问题:
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
Run Code Online (Sandbox Code Playgroud)
我得到一个错误说"调用可以抛出,但错误不能从全局变量初始化程序中抛出".我的应用程序依赖于它recorder是一个全局变量.有没有办法让它保持全球化,但解决这些问题?我不需要高级错误处理,我只是想让它工作.
bla*_*lau 19
如果您知道函数调用不会抛出异常,则可以调用throw函数try!来禁用错误传播.请注意,如果实际抛出错误,这将抛出运行时异常.
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject])
Run Code Online (Sandbox Code Playgroud)
San*_*eep 12
您可以使用3种方法来解决此问题.
用试试?
// notice that it returns AVAudioRecorder?
if let recorder = try? AVAudioRecorder(URL: soundFileURL, settings: recordSettings) {
// your code here to use the recorder
}
Run Code Online (Sandbox Code Playgroud)
用试试看!
// this is implicitly unwrapped and can crash if there is problem with soundFileURL or recordSettings
let recorder = try! AVAudioRecorder(URL: soundFileURL, settings: recordSettings)
Run Code Online (Sandbox Code Playgroud)
试着抓
// 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)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5574 次 |
| 最近记录: |