Skip to content

Instantly share code, notes, and snippets.

@zhjuncai
Forked from tomlokhorst/Optional+Unwrap.swift
Last active August 29, 2015 14:12
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 zhjuncai/2172f9f615338d7e26dc to your computer and use it in GitHub Desktop.
Save zhjuncai/2172f9f615338d7e26dc to your computer and use it in GitHub Desktop.
// 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment