重构两个 switch case 语句的代码

Refactor code for two switch case statement

我正在做一个 swift 项目,想重构我的代码。

我正在编写代码来检查用户是否在应用程序中同时授权了摄像头和麦克风授权。我写了下面的代码,但我想(我希望)我可以重构代码,因为我认为下面的代码不清楚。我理解了基本的 Swift 语法并逐渐理解了编译语言,但如果有办法使它更易读或更易于编写,请告诉我。

我想在这里做的是...

我所做的是,首先在checkAuthStatus中检查摄像头授权,然后,如果摄像头已授权,则触发checkMicrophoneStatus()来检查麦克风授权。 我认为这段代码不清楚的原因是,我只在 checkAuthStatus() 函数中写了一个检查相机授权的函数。我想如果很清楚我是否可以写类似

的东西
func checkAuthStatus(){
    // check both cameara and microphone is authorized.
    // if both of them are authorized, show next VC with showNextVC() function.
}

您可以将 checkCameraStatus() 和 checkMicrophoneStatus() 更改为 return 布尔值,并将 checkAuthStatus() 内部更改为:

func checkAuthStatus(){
    let cameraAuthorised = checkCameraStatus()
    let micAuthorised = checkMicrophoneStatus()

    if (cameraAuthorised && micAuthorised) {
        showNextVC()
    }
 }

一种方法是向两个函数添加一个 onAuthorised 闭包参数。这两个 checkXXXStatus 函数也有很多共同点。我们不需要复制 switch 语句。

func checkMediaStatus(type: AVMediaType, deviceName: String, onAuthorised: (() -> Void)?) {
    switch AVCaptureDevice.authorizationStatus(for: type){
    case .notDetermined:
        AVCaptureDevice.requestAccess(for: type) { granted in
            if granted {
                print("Now it's granted")
            }
        }
    case .restricted:
        print("restricted")
        showConfigurationAlert(for: deviceName)
    case .denied:
        print("denied")
        showConfigurationAlert(for: deviceName)
    case .authorized:
        print(("authorized"))
        onAuthorised?()
    @unknown default:
        print("unknown")
    }
}

func checkMicrophoneStatus(onAuthorised: (() -> Void)?) {
    checkMediaStatus(type: .audio, deviceName: "microphone", onAuthorised: onAuthorised)
}

func checkCameraStatus(onAuthorised: (() -> Void)?) {
    checkMediaStatus(type: .video, deviceName: "camera", onAuthorised: onAuthorised)
}

那么checkAuthStatus可以写成:

func checkAuthStatus(){
    checkCameraStatus {
        self.checkMicrophoneStatus {
            self.showNextVC()
        }
    }
}

另请注意,您可能还想在 requestAccess 完成处理程序中调用 onAuthorisedshowConfigurationAlert。我认为这是一个更好的设计。

if granted {
    print("Now it's granted")
    onAuthorised?()
} else {
    showConfigurationAlert(for: deviceName)
}

我想你正在寻找这样的东西:

let videoStatus = AVCaptureDevice.authorizationStatus(for: .video)
let audioStatus = AVCaptureDevice.authorizationStatus(for: .audio)

switch (videoStatus, audioStatus) {
case (.authorized, .authorized): showNextVC()
case (.authorized, _): showConfigurationAlert(for: "microphone")
case (_, .authorized): showConfigurationAlert(for: "camera")
default: print(videoStatus, audioStatus)
}

您可以同时检查两种情况,并按您喜欢的方式处理