Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Created October 11, 2018 22:13
Show Gist options
  • Select an option

  • Save jakehawken/b549d4aeccb0333515ad521c8cee6b07 to your computer and use it in GitHub Desktop.

Select an option

Save jakehawken/b549d4aeccb0333515ad521c8cee6b07 to your computer and use it in GitHub Desktop.
Optional assignment operator. (Discovered after writing this that it had already been thought of, suggested to, and rejected by Swift Evolution)
infix operator ??=
func ??=<T>(lhs: inout T, rhs: T?) {
guard let rhs = rhs else {
return
}
lhs = rhs
}
// This collapses and obviates redundant-looking use of the nil coalescing operator
// so that given this:
var x: Int = 4
var optionalX: Int? = nil
// instead of doing this:
x = optionalX ?? x
// you can instead do this:
x ??= optionalX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment