Skip to content

Instantly share code, notes, and snippets.

@oleganza
Last active August 29, 2015 14:02
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 oleganza/9805d0c42172803253a7 to your computer and use it in GitHub Desktop.
Save oleganza/9805d0c42172803253a7 to your computer and use it in GitHub Desktop.
Replacement for ?: operator in Clang
// Replacement for Clang's (a ?: b) in Swift.
// Note: does not yet handle case when 'false' is supplied as Any? or AnyObject? type.
operator infix ||| { associativity left precedence 140 }
// Version for arbitrary optionals.
@infix func |||<A>(a:A?, b: @auto_closure ()->A?) -> A? {
if let x = a {
return a
}
return b()
}
// Version for booleans:
@infix func |||(a:LogicValue?, b: @auto_closure ()->LogicValue?) -> LogicValue? {
if let x = a {
if x.getLogicValue() {
return a
}
}
return b()
}
// Examples:
var a:Int? // if a has value, neither b() not c() will be called.
func b() -> Int? {
println("side effect from b()");
return 2
}
func c() -> Int? {
println("side effect from c()");
return 3
}
var x = a ||| b() ||| c()
var f1:Bool? = false // if f1 is true, f2() won't be called
func f2() -> Bool {
println("side effect from f2()");
return true
}
var y = f1 ||| f2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment