Skip to content

Instantly share code, notes, and snippets.

@tomlokhorst
Last active December 26, 2017 19:50
Show Gist options
  • Save tomlokhorst/f9a826bf24d16cb5f6a3 to your computer and use it in GitHub Desktop.
Save tomlokhorst/f9a826bf24d16cb5f6a3 to your computer and use it in GitHub Desktop.
Unwrap multiple optionals in Swift 1.0
// 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!")
}
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
}
}
@tomlokhorst
Copy link
Author

As of Swift 1.2 this is no longer needed. if let supports multiple optionals:

if let a = foo(), b = bar() where a < b, let c = baz() {
}

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