Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check availability in switch statement

if a Enum type add new case in new os version,how to check availability in switch statement? Like a Enum in StoreKit below

public enum Code : Int {
    public typealias _ErrorType = SKError
    case unknown
    case clientInvalid 
    case paymentCancelled 
    case paymentInvalid 
    case paymentNotAllowed
    case storeProductNotAvailable
    @available(iOS 9.3, *)
    case cloudServicePermissionDenied 
    @available(iOS 9.3, *)
    case cloudServiceNetworkConnectionFailed
    @available(iOS 10.3, *)
    case cloudServiceRevoked
}

Is below code the only solution? It's too redundant.

if #available(iOS 10.3, *) {
    switch code {
        //all cases available in 10.3
        ...
    }
} else if #available(iOS 9.3, *) {
    switch code {
       //all cases available in 9.3
       ...
    }
} else {
    switch code {
        //all cases available below 9.3
        ...
    }
}

-----------------new-------------------------

I think It's not a question. All cases writed in one switch is fine, if statement is unneccessary. Because new added cases would not called in low iOS version.

like image 765
codiction Avatar asked Jun 02 '17 09:06

codiction


1 Answers

Usually it happens on a new versions of Xcode with fresh SDK and toolchain. So, for example Xcode 12 is bundled with iOS 14 SDK and Swift 5.3 and has a similar issues with new cases like PHAuthorizationStatus.limited which marked as available only in iOS 14 and it will break switch statement without default case.

As a workaround to make both version of Xcode 11 and Xcode 12 working I'd like to suggest following solution with checking Swift version:

    switch PHPhotoLibrary.authorizationStatus() {
    case .authorized:
        presentImagePicker()
    case .denied:
        presentAccessDeniedAlert()
    case .notDetermined:
        requestAuthorization()
    case .restricted:
        break
#if swift(>=5.3) // Xcode 12 iOS 14 support
    case .limited:
        presentImagePicker()
#endif
    @unknown default:
        assertionFailure()
    }
like image 61
Max Potapov Avatar answered Oct 14 '22 15:10

Max Potapov