Last active
August 29, 2015 14:02
-
-
Save oleganza/9805d0c42172803253a7 to your computer and use it in GitHub Desktop.
Replacement for ?: operator in Clang
This file contains hidden or 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
// 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