【问题标题】:Call can throw, but errors can not be thrown out of a global variable initializer调用可以抛出,但错误不能从全局变量初始化器中抛出
【发布时间】:2015-06-11 09:13:49
【问题描述】:

我使用的是 Xcode 7 beta,在迁移到 Swift 2 后,我遇到了这行代码的一些问题:

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

我收到一条错误消息,提示“调用可以抛出,但错误不能从全局变量初始化程序中抛出”。 我的应用程序依赖 recorder 作为全局变量。有没有办法让它保持全球性但解决这些问题?我不需要高级错误处理,我只想让它工作。

【问题讨论】:

    标签: swift swift2


    【解决方案1】:

    如果您知道您的函数调用不会抛出异常,您可以使用try! 调用抛出函数以禁用错误传播。请注意,如果实际抛出错误,这将抛出运行时异常。

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

    Source: Apple Error Handling documentation (Disabling Error Propagation)

    【讨论】:

      【解决方案2】:

      您可以使用 3 种方法来解决此问题。

      • 使用 try 创建可选的 AVAudioRecorder?
      • 如果你知道它会返回 AVRecorder,你可以隐式使用 try!
      • 或者然后使用 try / catch 处理错误

      使用 try?

      // 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)")
      }
      

      【讨论】:

        猜你喜欢
        • 2015-12-23
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-25
        • 2017-09-19
        • 2020-11-20
        • 2015-12-27
        相关资源
        最近更新 更多