用于条件绑定的 Swift Initializer 必须具有 Optional 类型,而不是 '[AVCaptureDevice]'
Posted
技术标签:
【中文标题】用于条件绑定的 Swift Initializer 必须具有 Optional 类型,而不是 \'[AVCaptureDevice]\'【英文标题】:Swift Initializer for conditional binding must have Optional type, not '[AVCaptureDevice]'用于条件绑定的 Swift Initializer 必须具有 Optional 类型,而不是 '[AVCaptureDevice]' 【发布时间】:2017-12-16 07:04:16 【问题描述】:我的 swift 项目中有以下代码
if let availabeDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone,
.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
captureDevice = availabeDevices.first
当我运行此代码时,如果行显示错误:
Initializer for conditional binding must have Optional type, not '[AVCaptureDevice]'
我尝试在.devices
之后添加?
,但出现了这个错误:
Cannot use optional chaining on non-optional value of type '[AVCaptureDevice]'
我该怎么办?
【问题讨论】:
【参考方案1】:使用下面的行。
if let captureDevice = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera],
mediaType: AVMediaType.video,
position: .back).devices.first
self.captureDevice = captureDevice
【讨论】:
【参考方案2】:在这里解释你的错误:
您收到错误是因为AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
返回[AVCaptureDevice]
而不是Optional
,如果您想使用if let
,那么RHS
应该始终是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
【讨论】:
以上是关于用于条件绑定的 Swift Initializer 必须具有 Optional 类型,而不是 '[AVCaptureDevice]'的主要内容,如果未能解决你的问题,请参考以下文章
Swift - NSIndex forRow inSection Initializer
Swift - 条件绑定的初始化程序必须具有可选类型,而不是 'PHFetchResult<PHAsset>'
条件绑定的初始化程序必须具有可选类型,而不是“字符串” - ios - swift
条件绑定的初始化程序必须具有可选类型,而不是“Substring.SubSequence”(又名“Substring”) - swift [重复]