Gregory Higley Gregory Higley - 1 year ago 148
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
too. My understanding is that the precedence group
already contains the
declaration, so this is unlikely to be the problem.

How can I do this in Swift 3?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download