Why does `+=` not work with implicitly unwrapped optionals

94 Views Asked by At

Why does += not work with implicitly unwrapped optionals, for instance:

var count: Int! = 10
count = count + 10 // This works
count += 10 // this does not work

Why isn't the optional implicitly unwrapped, like the case of count = count + 10 ?

1

There are 1 best solutions below

4
On

It doesn't work because the compound assignment operator += expects the left side to be a mutable Int variable. When you pass it count, the compiler unwraps the implicitly unwrapped optional and sends an immutable Int value instead, which cannot be passed as the inout parameter that += expects.

If you really want to do this, you can overload +=:

func += (left: inout Int!, right: Int) {
    left = left! + right
}

Now += sends the left side as an implicitly unwrapped optional without unwrapping it, and the unwrapping is done explicitly inside the function.

var count: Int! = 10
count = count + 10 // 20
count += 10 // 30