Skip to content

Instantly share code, notes, and snippets.

@nubbel
Created November 5, 2014 11:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nubbel/cde92a45a133228efb2e to your computer and use it in GitHub Desktop.
Save nubbel/cde92a45a133228efb2e to your computer and use it in GitHub Desktop.
infix operator ??= {
associativity right
precedence 90
assignment
}
func ??=<T>(inout optional: T?, defaultValue: @autoclosure () -> T?) -> T? {
optional = optional ?? defaultValue()
return optional
}
var x: Int? = 2
var y: Int? = nil
x ??= 99
x // => 2
y ??= 99
y // 99
@Jesbus
Copy link

Jesbus commented Dec 17, 2016

Thank you, I'm a noob in Swift and this is really nice to have :-)

@nubbel
Copy link
Author

nubbel commented Jan 17, 2017

@Jesbus glad you like it!

@Anton3
Copy link

Anton3 commented Feb 8, 2017

@nubbel Should be infix operator ??= : AssignmentPrecedence in Swift 3.

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