Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I return case values of switch statement? Swift 4

Tags:

swift

swift4

Trying to make a swift file with all kinds of permissions for iPhone including

  • Camera,
  • Photos library,
  • Contacts,
  • Location Services,
  • Microphone.

So I tried searching, How to know if user has access to Camera?

and mostly getting functions with Switch statements. What I am looking for is universal functions to call anywhere in project e:g after calling function elsewhere in project I want to able to perform if case .authorised then do code A elseif .denied then do code B else .notDetermined do code C.

func checkPhotoLibraryPermission() {
    let status = PHPhotoLibrary.authorizationStatus()
    switch status {
    case .authorized:
        print("Authorized")
    case .denied, .restricted :
    case .notDetermined:
        PHPhotoLibrary.requestAuthorization() { status in
            switch status {
            case .authorized:
                print("Authorized")
            case .denied, .restricted:
                print("No access")
            case .notDetermined:
                print("Not determined")
            }
        }
    }
}
like image 883
Harsh Avatar asked Nov 03 '25 15:11

Harsh


2 Answers

Yes, you can do this with the help of blocks.

public typealias CompletionHandler = ((Bool)->Void)?

  @objc func yourMethod(completionBlock : CompletionHandler){
    let status = PHPhotoLibrary.authorizationStatus()
    switch status {
    case .authorized:
        completionBlock(true);
    case .denied, .restricted :
         completionBlock(false);
    case .notDetermined:
        PHPhotoLibrary.requestAuthorization() { status in
            switch status {
            case .authorized:
                 completionBlock(true);
            case .denied, .restricted:
                 completionBlock(false);
            case .notDetermined:
                 completionBlock(false);
           }
        }
        }
    }

This is just a sample you can write accordingly.

like image 190
Jitendra Avatar answered Nov 05 '25 09:11

Jitendra


You need a callback function as PHPhotoLibrary.requestAuthorization() is an async operation.

func checkPhotoLibraryPermission(callback:(authorized:Bool)->Void) {
    let status = PHPhotoLibrary.authorizationStatus()
    switch status {
    case .authorized:
        callback(true)
    case .denied, .restricted :
         callback(false)
    case .notDetermined:
        PHPhotoLibrary.requestAuthorization() { status in
            switch status {
            case .authorized:
                 callback(true)
            case .denied, .restricted,.notDetermined:
                 callback(false)
           }
        }
    }
}
like image 23
LHIOUI Avatar answered Nov 05 '25 09:11

LHIOUI



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!