[英]Swift Initializer for conditional binding must have Optional type, not '[AVCaptureDevice]'
I have this following code in my swift project我的 swift 项目中有以下代码
if let availabeDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone,
.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices {
captureDevice = availabeDevices.first
}
When i run this code it gives me an error on if line that reads:当我运行此代码时,它在 if 行上给我一个错误:
Initializer for conditional binding must have Optional type, not '[AVCaptureDevice]'
I tried adding ?
我尝试添加?
after .devices
,but that gave this error:在.devices
之后,但这给出了这个错误:
Cannot use optional chaining on non-optional value of type '[AVCaptureDevice]'
What do i do?我该怎么办?
Use below lines.使用以下几行。
if let captureDevice = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera],
mediaType: AVMediaType.video,
position: .back).devices.first {
self.captureDevice = captureDevice
}
Explaining your error here:在此处解释您的错误:
You are getting error because AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
returns [AVCaptureDevice]
which is not Optional
and if you want to use if let
then RHS
should be always Optional
.您收到错误是因为AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
返回[AVCaptureDevice]
这不是Optional
,如果您想使用if let
then RHS
应该总是Optional
。
if you want to get rid of this error you need to make AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
as Optional
by adding as? [AVCaptureDevice]
如果你想摆脱这个错误,你需要将AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
添加as? [AVCaptureDevice]
Optional
as? [AVCaptureDevice]
at the end of it. as? [AVCaptureDevice]
在它的末尾。
And your code will be:你的代码将是:
if let availabeDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone,
.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices as? [AVCaptureDevice] {
let captureDevice = availabeDevices.first
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.