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

时间:2017-06-25 20:04:56

标签: swift xcode avcapturesession do-catch

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

  

使用未解析的标识符'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变量。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

captureDeviceInput在本地声明,表示它仅在do范围内可见。

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

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