Skip to content

Instantly share code, notes, and snippets.

@daehn
Forked from radex/optional-assignment.swift
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daehn/8d6188706405cae200ab to your computer and use it in GitHub Desktop.
Save daehn/8d6188706405cae200ab 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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment