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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With