Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `+=` not work with implicitly unwrapped optionals [duplicate]

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 ?

like image 608
Muhammad Zubair Ghori Avatar asked Oct 29 '22 04:10

Muhammad Zubair Ghori


1 Answers

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
like image 152
Robert Avatar answered Nov 15 '22 07:11

Robert