Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Last active August 29, 2015 14:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/5463632e1001ef4a9160 to your computer and use it in GitHub Desktop.
Save airspeedswift/5463632e1001ef4a9160 to your computer and use it in GitHub Desktop.
func optional_pair1<T,U>(t: T?, u: U?)->String {
switch (t,u) {
// every case exhaustively covers the possibilities
case (.None,.None): return "neither"
case let (.Some(t), .Some(u)): return "both"
case let (.Some(t),.None): return "left"
case let (.None,.Some(u)): return "right"
// so no need for a default clause at all
// this way, you are totally explicit about
// which case is being handled how.
// deleting any of the four cases = compilation error
}
}
let combos: [(Int?,Int?)] = [
( 1, 2),
(nil, 2),
( 1, nil),
(nil, nil),
]
for desc in combos.map(optional_pair1) {
println(desc)
}
func optional_pair2<T,U>(t: T?, u: U?)->String {
switch (t,u) {
// you can even leave off the .Some:
case (nil,nil): return "neither"
case let (t,nil): return "left"
case let (nil,u): return "right"
// but BEWARE! this last case is
// secretly a default, because
// it will also match nil values.
// make sure it comes last...
case let (t, u): return "both"
// (sometimes this behaviour can be useful)
}
}
for desc in combos.map(optional_pair2) {
println(desc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment