Skip to content

Instantly share code, notes, and snippets.

@jhaberstro
Last active August 29, 2015 14:02
Show Gist options
  • Save jhaberstro/878f7f2043f922f0d06c to your computer and use it in GitHub Desktop.
Save jhaberstro/878f7f2043f922f0d06c to your computer and use it in GitHub Desktop.
Multiple optional bindings in Swift (i.e. the equivalent of if let (a, b, c) = (optA, optB, optC) { ... })
// The DSL's implementation (i.e. just the applicative interface for Optionals + methods for creating tuples)
operator infix <*> { associativity left }
@infix func <*><A, B>(lhs: (A -> B)?, rhs: A?) -> B? {
switch lhs {
case .None:
return .None
case let .Some(f):
return rhs.map(f)
}
}
operator infix => { associativity left }
@infix func =><A, B>(f: A -> B, x: A?) -> B? {
return x.map(f)
}
func zip<A, B>(a: A)(b: B) -> (A, B) {
return (a, b)
}
func zip<A, B, C>(a: A)(b: B)(c: C) -> (A, B, C) {
return (a, b, c) // segfault - seems to a be a compiler bug in code-gen
}
// Example usage
var a: Int[]? = [5]
var s: String? = "5"
var f: Float? = 5.0
println("Before zip")
if let (av, sv, fv) = (zip => a <*> s <*> f) {
println("\(av) and \(sv) and \(fv)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment