2

我的 swift 项目中有以下代码

if let availabeDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone,
.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices {

            captureDevice = availabeDevices.first
        }

当我运行此代码时,它在 if 行上显示错误:

Initializer for conditional binding must have Optional type, not '[AVCaptureDevice]'

我尝试?在之后添加.devices,但这给出了这个错误:

Cannot use optional chaining on non-optional value of type '[AVCaptureDevice]'

我该怎么办?

4

2 回答 2

3

使用下面的行。

if let captureDevice = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], 
mediaType: AVMediaType.video, 
position: .back).devices.first {
            self.captureDevice = captureDevice
        }
于 2017-12-16T07:09:35.887 回答
2

在这里解释你的错误:

您收到错误是因为AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices返回[AVCaptureDevice]的不是Optional,如果您想使用if letthenRHS应该是 always Optional

如果你想摆脱这个错误,你需要在它AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices的末尾Optional添加。as? [AVCaptureDevice]

您的代码将是:

if let availabeDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone,
                                                                            .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices as? [AVCaptureDevice] {

    let captureDevice = availabeDevices.first
}
于 2017-12-16T07:13:33.290 回答