【问题标题】:Use of unresolved identifier when referencing variable in do/catch block在 do/catch 块中引用变量时使用未解析的标识符
【发布时间】:2017-11-28 17:27:15
【问题描述】:

我在 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 变量。我该怎么做才能解决这个问题?

【问题讨论】:

  • 我不认为我跟随。 do 块是一个块,因此 captureDeviceInput(以及其中声明的任何其他内容)的范围仅限于该块,您不能在其他任何地方使用它
  • @crizzis 是的。这就是我需要知道的。你可能会说,我是 Swift n00b!

标签: swift xcode avcapturesession do-catch


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的快速回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2019-06-08
  • 2015-05-13
相关资源
最近更新 更多