Gregory Higley Gregory Higley - 1 month ago 18
Swift Question

Null-coalescing assignment operator in Swift 3

I'm trying to create a null-coalescing assignment operator in Swift 3. In other words, instead of this:

x = x ?? y


I want this:

x ??= y


Swift 3 does not seem to like my operator. Here's its definition:

infix operator ??= : AssignmentPrecedence
func ??=(lhs: inout Any?, rhs: @autoclosure () -> Any?) {
if lhs != nil { return }
lhs = rhs()
}
var x = 3
x ??= 7 // Cannot convert value of type 'Int' to expected argument type 'inout Any?'.


I've done it without the
@autoclosure
too. My understanding is that the precedence group
AssignmentPrecedence
already contains the
assignment
declaration, so this is unlikely to be the problem.

How can I do this in Swift 3?

Answer

First, make the operator generic instead of using Any:

infix operator ??= : AssignmentPrecedence
func ??=<T>(lhs: inout T?, rhs: @autoclosure () -> T?) {
    if lhs != nil { return }
    lhs = rhs()
}

Second, the left operand needs to be an optional (otherwise it could not be tested against nil):

var x: Int? = 3
x ??= 7
Comments