Created
June 21, 2014 15:01
-
-
Save rgcottrell/c42e62d1f09e711f54b5 to your computer and use it in GitHub Desktop.
Unwrapping Multiple Swift Optionals
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
// NOTE: @schwa figured this out, but I'm claiming some of the credit for asking the question. | |
// See https://gist.github.com/schwa/ecd5f8c154e60fcb0f58 for the original solution. | |
// Playground - noun: a place where people can play | |
import Foundation | |
// Implementation (repeat as needed for number of parameters). | |
func unwrap<T1, T2>(p1: T1?, p2: T2?) -> (T1, T2)? { | |
// return p1 && p2 ? (p1!, p2!) : nil | |
if p1 && p2 { | |
return (p1!, p2!) | |
} | |
return nil | |
} | |
func unwrap<T1, T2, T3>(p1: T1?, p2: T2?, p3: T3?) -> (T1, T2, T3)? { | |
// return p1 && p2 && p3 ? (p1!, p2!, p3!) : nil | |
if p1 && p2 && p3 { | |
return (p1!, p2!, p3!) | |
} | |
return nil | |
} | |
// Example | |
var a: String? = "A" | |
var b: String? = "B" | |
var c: String? = "C" | |
// New hotness | |
if let (x, y, z) = unwrap(a, b, c) { | |
x | |
y | |
z | |
} else { | |
"There was at least one nil" | |
} | |
// Old and busted | |
if a && b && c { | |
let (x, y, z) = (a!, b!, c!) | |
x | |
y | |
z | |
} else { | |
"There was at least on nil" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment