可以抛出调用,但是不能从全局变量初始化程序中抛出错误 [英] Call can throw, but errors can not be thrown out of a global variable initializer

查看:200
本文介绍了可以抛出调用,但是不能从全局变量初始化程序中抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Xcode 7 Beta,并且在迁移到Swift 2之后,我遇到了以下代码行问题:

I'm using Xcode 7 beta and after migrating to Swift 2 I experienced some issues with this line of code:

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

我收到一条错误消息:可以抛出调用,但是不能从全局变量初始化程序中抛出错误". 我的应用程序依赖recorder作为全局变量.有没有办法使它保持全球性,但可以解决这些问题?我不需要高级错误处理,我只希望它能正常工作.

I get an error saying "Call can throw, but errors can not be thrown out of a global variable initializer". My app relies on the recorder to be a global variable. Is there a way to keep it global but fix these issues? I have no need for advanced error handling, I just want it to work.

推荐答案

如果您知道函数调用不会引发异常,则可以使用try!调用throwing函数以禁用错误传播.请注意,如果实际抛出错误,则会抛出运行时异常.

If you know that your function call will not throw an exception, you can call the throwing function with try! to disable error propagation. Note that this will throw a runtime exception if an error is actually thrown.

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

来源:Apple错误处理文档(禁用错误传播)

这篇关于可以抛出调用,但是不能从全局变量初始化程序中抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆