Skip to content

Instantly share code, notes, and snippets.

@qnoid
Last active May 25, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qnoid/655795656b7200e128f869e889ab7734 to your computer and use it in GitHub Desktop.
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.
// 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)
}
}
@qnoid
Copy link
Author

qnoid commented May 25, 2016

The requirement is to create a LocalAuthentication instance only if the given AuthenticationLevel (an enum) is AuthenticationLevelZero 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment