2

I have this following code in my swift project

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:

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

I tried adding ? after .devices,but that gave this error:

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

What do i do?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
askoasksao
  • 87
  • 1
  • 7

2 Answers2

3

Use below lines.

if let captureDevice = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone, .builtInWideAngleCamera], 
mediaType: AVMediaType.video, 
position: .back).devices.first {
            self.captureDevice = captureDevice
        }
2

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.

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] at the end of it.

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
}
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165