Last active
December 26, 2017 19:50
-
-
Save tomlokhorst/f9a826bf24d16cb5f6a3 to your computer and use it in GitHub Desktop.
Unwrap multiple optionals in Swift 1.0
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
// To wrap two optionals at once: | |
if let (firstName, lastName) = unwrap(optionalFirstName, optionalLastName) { | |
println("Hello \(firstName) \(lastName)!") | |
} | |
// Note, if you want to actually handle all four different cases, you can use the switch statement. | |
switch (optionalFirstName, optionalLastName) { | |
case let (.Some(firstName), .Some(lastName)): | |
println("Hello \(firstName) \(lastName)!") | |
case let (.Some(firstName), .None): | |
println("Hi \(firstName)!") | |
case let (.None, .Some(lastName)): | |
println("Greetings \(lastName).") | |
case let (.None, .None): | |
println("Good day to you!") | |
} |
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
func unwrap<T1, T2>(optional1: T1?, optional2: T2?) -> (T1, T2)? { | |
switch (optional1, optional2) { | |
case let (.Some(value1), .Some(value2)): | |
return (value1, value2) | |
default: | |
return nil | |
} | |
} | |
func unwrap<T1, T2, T3>(optional1: T1?, optional2: T2?, optional3: T3?) -> (T1, T2, T3)? { | |
switch (optional1, optional2, optional3) { | |
case let (.Some(value1), .Some(value2), .Some(value3)): | |
return (value1, value2, value3) | |
default: | |
return nil | |
} | |
} | |
func unwrap<T1, T2, T3, T4>(optional1: T1?, optional2: T2?, optional3: T3?, optional4: T4?) -> (T1, T2, T3, T4)? { | |
switch (optional1, optional2, optional3, optional4) { | |
case let (.Some(value1), .Some(value2), .Some(value3), .Some(value4)): | |
return (value1, value2, value3, value4) | |
default: | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As of Swift 1.2 this is no longer needed.
if let
supports multiple optionals: