Created
June 3, 2014 17:57
-
-
Save barrettj/c662c2e646b7f8b75fa0 to your computer and use it in GitHub Desktop.
Custom Ternary Shorthand
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
import Cocoa | |
operator infix ~~ {} | |
@infix func ~~ (left: Any?, right: Any?) -> Any? { | |
if let temp = left { | |
return temp | |
} | |
if let temp = right { | |
return temp | |
} | |
return nil | |
} | |
let isSet:NSString? = "I'm isSet" | |
let notSet:NSString? | |
let test1 = notSet ~~ isSet | |
let test2 = isSet ~~ notSet | |
Could also do:
@infix func ~~ (left: Any?, right: Any?) -> Any {
if let temp = left {
return temp
}
assert(right)
return right!
}
Which will give you a non-nillable, but will fail the assert if you ever pass a nil value to the right hand.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output of both test1 and test2 will be a nillable version of isSet