Last active
May 25, 2016 14:18
-
-
Save qnoid/655795656b7200e128f869e889ab7734 to your computer and use it in GitHub Desktop.
How using an "Optional Pattern" alongside an "Enumeration Case Pattern" in Swift reduces the code it takes to match an optional AND an enum case at once while capturing its associated values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: - guard without Optional Pattern | |
extension LocalAuthentication { | |
convenience init?(authenticationLevel: AuthenticationLevel?){ | |
guard let authenticationLevel = authenticationLevel else { | |
return nil | |
} | |
switch authenticationLevel { | |
case .AuthenticationLevelZero(let mobile, let deviceId, _): | |
self.init(deviceConfiguration: DeviceConfiguration(deviceId: deviceId), mobile: mobile) | |
default: | |
return nil | |
} | |
} | |
} | |
// MARK: - guard with Optional Pattern | |
extension LocalAuthentication { | |
convenience init?(authenticationLevel: AuthenticationLevel?){ | |
guard case let .AuthenticationLevelZero(mobile, deviceId, _)? = authenticationLevel else { | |
return nil | |
} | |
self.init(deviceConfiguration: DeviceConfiguration(deviceId: deviceId), mobile: mobile) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The requirement is to create a
LocalAuthentication
instance only if the givenAuthenticationLevel
(an enum) isAuthenticationLevelZero
while also getting its associated values.Ref: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html#//apple_ref/swift/grammar/enum-case-pattern