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
?
It doesn't work because the compound assignment operator
+=
expects the left side to be a mutableInt
variable. When you pass itcount
, the compiler unwraps the implicitly unwrapped optional and sends an immutableInt
value instead, which cannot be passed as theinout
parameter that+=
expects.If you really want to do this, you can overload
+=
:Now
+=
sends the left side as an implicitly unwrapped optional without unwrapping it, and the unwrapping is done explicitly inside the function.