Hien Quang Tran Hien Quang Tran - 7 months ago 6
Swift Question

Are ++ and +=1 exactly the same?

I just switch to Swift for couple days and I notice that the postfix and prefix ++ and -- will be removed in Swift 3. I have done some research and according to the announcement on the Swift website, the operator ++ and -- will be replaced by += 1 and -= 1. Link here New Features in Swift 2.2

I have a piece of code that work just fine with the old version of Swift. When I change from

return counter1++
which is my original code to
return counter1 += 1
and an error pops up saying


No '+=' candidates produce the expected contextual type 'Int'


Here is my example

func countingCounter() -> (() -> Int){
var counter1 = 0
let incrementCounter1: () -> Int = {
return counter1+=1 //original is counter1++
}
return incrementCounter1
}


I have tried to work this out but still stuck. Please help me.

Thank you very much.

Answer

As said in my comment here is how you have to write it now to replace the postfix ++. ANother way would be to use an intermediary variable if you don't like the -1 thing.

let incrementCounter1: () -> Int = {
    counter1+=1   //original is counter1++
    return counter1-1;
}
Comments