Skip to content

Instantly share code, notes, and snippets.

@radex
Last active February 29, 2016 13:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save radex/68de9340b0da61d43e60 to your computer and use it in GitHub Desktop.
Save radex/68de9340b0da61d43e60 to your computer and use it in GitHub Desktop.
Optional assignment operator implementation. `foo ??= bar` will evaluate and assign bar to foo if and only if foo is nil. Equivalent to `||=` in Ruby and other languages.
infix operator ??= {
associativity right
precedence 90
assignment
}
func ??= <T>(inout variable: T?, expr: @autoclosure () -> T) {
if variable == nil {
variable = expr()
}
}
@semireg
Copy link

semireg commented Oct 29, 2015

Why isn't this change merged into the SwiftyUserDefaults project?

@radex
Copy link
Author

radex commented Nov 1, 2015

Why isn't this change merged into the SwiftyUserDefaults project?

@semireg Because it's not User Defaults-specific, and although I like this operator, I don't want to add it to everyone's code in an unrelated project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment