Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when converting to current syntax

Last year, I did a tutorial on how to create a camera app. Today I tried to run it but it needed to be converted to the current syntax. After fixing a majority of the errors, I'm now left with just one error that I can't fix. I'm not too familiar with AVFoundation or Swift 4 yet so I was hoping that I could receive some sort of assistance. The error that Im getting is on line 61/62:

"Initializer for conditional binding must have optional type, not [AVCaptureDevice]"

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

Here's the relevant code:

//capture devices
func configureCaptureDevices() throws {
    let session = AVCaptureDevice.DiscoverySession(deviceTypes: [], mediaType: <#T##AVMediaType?#>, position: <#T##AVCaptureDevice.Position#>)
    guard let cameras = (session.devices.flatMap { $0 }), !cameras.isEmpty else { throw CameraControllerError.noCamerasAvailable}

    for camera in cameras {
        if camera.position == .front {
            self.frontCamera = camera
        }

        if camera.position == .back {
            self.rearCamera = camera

            try camera.lockForConfiguration()
            camera.focusMode = .continuousAutoFocus
            camera.unlockForConfiguration()
        }

    }
}

And finally, a link to the tutorial I was following: https://www.appcoda.com/avfoundation-swift-guide/

like image 668
Vandal Avatar asked Mar 22 '26 01:03

Vandal


1 Answers

The problem is that you're using guard let syntax which is only for binding optionals. And you've correctly deduced that session is no longer optional (which is why you removed the ?). So pull the assignment of cameras out of the guard statement:

let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .unspecified)
let cameras = session.devices.flatMap { $0 }
guard !cameras.isEmpty else { throw CameraControllerError.noCamerasAvailable }

Personally, now that we're no longer doing any optional binding, I'd replace that guard statement with a more intuitive if statement. I also don't believe that flatMap is needed (you use that when dealing with arrays of arrays or arrays of optionals, neither of which applies here):

let cameras = session.devices
if cameras.isEmpty { throw CameraControllerError.noCamerasAvailable }
like image 123
Rob Avatar answered Mar 24 '26 13:03

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!