简体   繁体   中英

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

I have a class to handle movie recording with AVFoundation. The initializer will throw an error if any part of the setup fails. The failure error:

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

This occurs when trying to create a variable from an initializer that also throws an error if initialization fails.

let captureInputDevice = try AVCaptureDeviceInput(device: device)

Code:

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
        }
      }
    }
  }
}

Question

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

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

Yes. You are doing a do...catch inside a non-failable initializer. This means there are circumstances remaining where initialization might not correctly take place. You must finish initialization before you can throw. For example, in the code you've shown, if you add super.init() as the first line of the initializer, all is well, because you have finished initialization before throwing.

You might be more comfortable, if initialization can fail, writing a failable initializer ( init? ).

EDIT: Please note that in starting in Swift 2.2, this requirement will be lifted: it will be legal to throw before finishing initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM