Shorthand for assignment if nil in Swift?

Check this out, put the following in global code space(In your Extensions.swift maybe). This creates a custom operator you can use throughout your entire project.

Swift 2

infix operator ??= {}
func ??= <T>(inout left: T?, right: T) {
    left = left ?? right
}

Swift 3

infix operator ??=
func ??= <T>(left: inout T?, right: T) {
    left = left ?? right
}

Usage:

var foo: String? = nil
var bar = "Bar"
foo ??= bar
print("Foo: \(bar)")

Hope this helps :)


Laffen’s answer is great. However, it is not exactly equivalent to x = x ?? y as the right hand side is always evaluated with their definition of ??= as opposed to the standard ?? operator.

If you want to have this behavior too, @autoclosure is here to help:

infix operator ??=
func ??=<T>(left: inout T?, right: @autoclosure () -> T) {
    left = left ?? right()
}

Tags:

Swift