Last active
December 14, 2015 17:30
-
-
Save MartinJNash/a1c9cff1d4af675f03b2 to your computer and use it in GitHub Desktop.
Ruby Crowbar Operator in Swift
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 | |
infix operator ||= {} | |
func ||= <T> (inout value: T?, newValue: @autoclosure () -> T) -> T { | |
if value == nil { | |
value = newValue() | |
} | |
return value! | |
} | |
func ||= <T> (inout value: T, newValue: @autoclosure () -> T) -> T { | |
return value | |
} | |
var myString: String? | |
myString ||= "Not nil anymore" | |
myString ||= "ALREADY SET, So no change" | |
myString |
infix operator ||= {}
func ||=<A> (inout left: A?, right: @autoclosure ()->A) {
left = left ?? right()
}
func ||=<A> (inout left: A, right: @autoclosure ()->A) {
// no op
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For assignment only, it's not necessary to return anything from these methods.