在 do/catch 块中引用变量时使用未解析的标识符

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

我在 do / catch 块中分配一个变量,然后尝试在我的文件中进一步引用该变量。但是当我这样做时,我在 Xcode 中收到以下错误:

Use of unresolved identifier 'captureDeviceInput'

这是我的代码:

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

captureSession = AVCaptureSession()

captureSession?.addInput(input: captureDeviceInput as AVCaptureDeviceInput)

似乎 Xcode 没有识别 captureDeviceInput 变量。我该怎么做才能解决这个问题?

captureDeviceInput 在本地声明,这意味着它仅在 do 范围内可见。

将所有好的代码也放在do范围内是个好习惯。

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