Search code examples
swiftoptional-binding

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


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?


Solution

  • Use below lines.

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