class 实例的所有存储属性必须在从初始化器抛出之前初始化

All stored properties of a class instance must be initialized before throwing from an initializer

我有一个 class 来处理 AVFoundation 的电影录制。如果设置的任何部分失败,初始化程序将抛出错误。失败错误:

"All stored properties of a class instance must be initialized before throwing from an initialize"

尝试从初始化程序创建变量时会发生这种情况,如果初始化失败也会引发错误。

let captureInputDevice = try AVCaptureDeviceInput(device: device)

代码:

enum MovieRecorderError : ErrorType {
  case CouldNotInitializeCamera
}

class MovieRecorder: NSObject {

  init(previewLayer: UIView) throws {  
    // Scan through all available AV capture inputs
    for device in AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice] {
      if device.position == .Back {
        do {
          let captureInputDevice = try AVCaptureDeviceInput(device: device)
        } catch {
          throw MovieRecorderError.CouldNotInitializeCamera
        }
      }
    }
  }
}

问题

这个问题是在一个抛出错误的函数中实例化一个抛出错误的变量引起的吗?

Is this problem caused by instantiating a variable that throws an error, inside a function that throws an error?

是的。您正在一个不可失败的初始值设定项中执行 do...catch。这意味着在某些情况下可能无法正确进行初始化。必须先完成初始化才能抛出。例如,在您显示的代码中,如果您将 super.init() 添加为初始化程序的 first 行,那么一切都很好,因为您在抛出之前已经完成了初始化。

如果初始化可能失败,您可能会更舒服,编写一个可失败的初始化程序 (init?)。

编辑: 请注意,从 Swift 2.2 开始,此要求将被取消:抛出 before 完成初始化。