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

Charles Srstka cocoadev at charlessoft.com
Sun Nov 5 09:36:07 CST 2017


> On Nov 5, 2017, at 9:27 AM, Dennis Weissmann <dennis at dennisweissmann.me> wrote:
> 
> 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

Hi Dennis,

The compiler warning is correct. That default *will* never be executed, because if one of the .touchID cases comes up, control flow will go to the .biometry cases.

Although it’s bridged to Swift, LAError is a C enum, which is just an integer. So if the framework set it to .biometryNotAvailable, it’s -6. If the framework code spelled it .touchIDNotAvailable, it’s still -6. And C has no way to distinguish between the two; -6 is -6. So your .biometryNotAvailable case will catch it either way. You can delete the default case here, and your switch will still be exhaustive (unless Apple adds additional cases to the enum in the future, of course).

Charles

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


More information about the swift-users mailing list