[swift-users] Handle deprecated enum cases from a library

Dennis Weissmann dennis at dennisweissmann.me
Sun Nov 5 09:27:42 CST 2017


Hi Charles,

I do believe you :)

The problem is that this doesn't work without a compiler warning if you switch over every case except for the deprecated ones because then the compiler warns that "default will never be executed".

As per my first mail feel free to try this out in a playground:

private func handleLocalAuthenticationError(_ error: LAError) {
    switch error.code {
    case .userCancel, .appCancel, .systemCancel:
        // Handle cancelation
    case .authenticationFailed:
        // Handle failure
    case .passcodeNotSet:
        // Handle passcode absence
    case .biometryNotEnrolled:
        // Handle no biometry enrollment
    case .biometryNotAvailable:
        // Handle no biometry availabe
    case .biometryLockout:
        // Handle biometry Lockout
    case .userFallback:
        // Handle user fallback
    case .invalidContext:
        // Handle failure with invalid context
    case .notInteractive:
        // Handle no interaction allowed error
    default:                                     // <- Here the compiler emits a warning that the default will never be executed.
        // hopefully only deprecated cases
        break
    }
}

- Dennis

> On Nov 5, 2017, at 4:13 PM, Charles Srstka <cocoadev at charlessoft.com> wrote:
> 
>> On Nov 5, 2017, at 3:14 AM, Dennis Weissmann <dennis at dennisweissmann.me> wrote:
>> 
>> Hi Charles,
>> 
>> You are right (the `default` case would not catch the deprecated values but only new ones introduced in future releases), but the compiler doesn’t seem to know that :(
>> 
>> But now that you say it, one approach could be to pattern match the raw values (and, well, have a default clause, which I really want to avoid) 🤔
>> 
>> - Dennis
>> 
>> Sent from my iPhone
> 
> Hi Dennis,
> 
> What I am saying is that the new cases have the same raw values as the old ones. touchIDNotAvailable is -6; biometryNotAvailable is -6. touchIDNotEnrolled is -7; biometryNotEnrolled is -7. touchIDLockout it -8; biometryLockout is -8. They’re just aliases to each other, so if you handle one, you don’t have to handle the other. You can literally ignore the deprecated values and treat them as if they don’t exist. Try this code for yourself if you don’t believe me:
> 
> let err = LAError.touchIDLockout
> 
> switch err {
> case LAError.biometryLockout:
> 	print("biometry lockout")
> default:
> 	print("default")
> }
> 
> This prints “biometry lockout”.
> 
> Charles
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171105/91c02d7d/attachment.html>


More information about the swift-users mailing list