Skip to content

Instantly share code, notes, and snippets.

@MartinJNash
Last active December 14, 2015 17:30
Show Gist options
  • Save MartinJNash/a1c9cff1d4af675f03b2 to your computer and use it in GitHub Desktop.
Save MartinJNash/a1c9cff1d4af675f03b2 to your computer and use it in GitHub Desktop.
Ruby Crowbar Operator in Swift
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
@MartinJNash
Copy link
Author

For assignment only, it's not necessary to return anything from these methods.

@MartinJNash
Copy link
Author

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