我似乎无法制作自定义相机。 "Constant used before initialized"

I can't seem to make a custom camera. "Constant used before initialized"

我正在使用 swift 3. 我正在尝试制作自定义相机。但是无论我按照多少教程,或者苹果文档,总是有错误。

class ViewController: UIViewController, UIImagePickerControllerDelegate {

@IBOutlet var cameraView: UIView!

var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080

    let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    let error : NSError?

    do {

        let input = try! AVCaptureDeviceInput (device: backCamera)
        if (error == nil && captureSession?.canAddInput(input) != nil) {

            captureSession?.addInput(input)

            stillImageOutput = AVCaptureStillImageOutput()
            stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

            if (captureSession?.canAddOutput(stillImageOutput) != nil) {
                captureSession?.addOutput(stillImageOutput)

                previewLayer = AVCaptureVideoPreviewLayer (session: captureSession)
                previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                cameraView.layer.addSublayer(previewLayer!)
                captureSession?.startRunning()
            }
        }
    } catch {

    }
}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    previewLayer?.frame = cameraView.bounds
}

这一行,if (error == nil && captureSession?.canAddInput(input) != nil) {,有一个错误说常量"error"在初始化之前已经被使用。我真的不明白这一点。提前谢谢你。

如错误消息所述,您在初始化之前使用了 error。您可以通过使用 nil:

对其进行初始化来解决此问题
let error: NSError? = nil

甚至更好:

let error: Error? = nil

实际上,您从未使用过 error,因此您可以简单地删除它:

...
//let error : NSError? delete this line

do {
    ...
    if (/* error == nil && delete this */captureSession?.canAddInput(input) != nil) {