Search code examples
swiftxcodeavcapturesessiondo-catch

Use of unresolved identifier when referencing variable in do/catch block


I’m assigning a variable in a do / catch block, and then trying to reference that variable further down in my file. But when I do, I get the following error in Xcode:

Use of unresolved identifier 'captureDeviceInput'

This is my code:

do {
    let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput
} catch let error {
    print("\(error)")
    return
}

captureSession = AVCaptureSession()

captureSession?.addInput(input: captureDeviceInput as AVCaptureDeviceInput)

It seems Xcode’s not recognising the captureDeviceInput variable. What can I do to resolve this?


Solution

  • captureDeviceInput is declared locally that means it's visible only in the do scope.

    It's good habit to put all good code also in the do scope.

    do {
        let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput
        captureSession = AVCaptureSession()
        captureSession?.addInput(input: captureDeviceInput as AVCaptureDeviceInput)
    } catch {
        print("\(error)")
        return
    }