Why `+ =` does not work with implicitly expanded options

Why += does not work with implicitly deployed options, for example:

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

Why is optional optional unfolding, as is the case with count = count + 10 ?

+5
source share
1 answer

This does not work because the compound assignment operator += expects the left side to be a mutable variable Int . When you pass it count , the compiler expands the implicitly expanded option and sends an immutable Int value instead, which cannot be passed as the inout 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 expanded option without expanding it, and the expansion is performed explicitly inside the function.

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

Source: https://habr.com/ru/post/1270172/


All Articles