Skip to content

Instantly share code, notes, and snippets.

@barrettj
Created June 3, 2014 17:57
Show Gist options
  • Save barrettj/c662c2e646b7f8b75fa0 to your computer and use it in GitHub Desktop.
Save barrettj/c662c2e646b7f8b75fa0 to your computer and use it in GitHub Desktop.
Custom Ternary Shorthand
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
@barrettj
Copy link
Author

barrettj commented Jun 3, 2014

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