去年,我做了一个关于如何创建相机应用程序的教程。今天我尝试运行它,但需要将其转换为当前语法。在解决了大部分错误之后,我现在只剩下一个我无法解决的错误。我对AVFoundation或Swift 4不太熟悉,所以我希望能得到某种帮助。我得到的错误在第61/62行:
条件绑定的初始化程序必须具有可选类型,而不是[AVCaptureDevice]
以下是相关代码:
//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()
}
}
}
最后,链接到我关注的教程:https://www.appcoda.com/avfoundation-swift-guide/
答案 0 :(得分:3)
问题是您使用的guard let
语法仅用于绑定选项。并且您已正确推断session
不再是可选的(这就是您删除?
的原因)。因此,从cameras
语句中删除guard
的分配:
let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .unspecified)
let cameras = session.devices.flatMap { $0 }
guard !cameras.isEmpty else { throw CameraControllerError.noCamerasAvailable }
就个人而言,既然我们不再进行任何可选绑定,我会用更直观的guard
语句替换if
语句。我也不相信需要flatMap
(在处理数组数组或选项数组时使用它,这两个都不适用于此处):
let cameras = session.devices
if cameras.isEmpty { throw CameraControllerError.noCamerasAvailable }