Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does ++ exactly mean in Swift?

i am learning Swift with a book aimed for people with little experience. One thing bothering me is the ++ syntax. The following is taken from the book:

var counter = 0
let incrementCounter = {
  counter++
}
incrementCounter()
incrementCounter()
incrementCounter()
incrementCounter()
incrementCounter()

the book said counter is 5.

but i typed these codes in an Xcode playground. It is 4!

i am confused.

like image 288
Tang1230 Avatar asked Jan 06 '23 13:01

Tang1230


2 Answers

The post-increment and post-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's original value prior to the increment (or decrement) operation

So when you see playground, current value of counter is being printed.

playground

But after evaluation of function, the value of counter changes and you can see updated value on the next line.

like image 145
saurabh Avatar answered Jan 18 '23 02:01

saurabh


x++ operator is an operator that is used in multiple languages - C, C++, Java (see the C answer for the same question)

It is called post-increment. It increments the given variable by one but after the current expression is evaluated. For example:

var x = 1
var y = 2 + x++
// the value of x is now 2 (has been incremented)
// the value of y is now 3 (2 + 1, x has been evaluated before increment)

This differs from the ++x (pre-increment) operator:

var x = 1
var y = 2 + ++x
// the value of x is now 2 (has been incremented)
// the value of y is now 4 (2 + 4, x has been evaluated after increment)

Note the operator is getting removed in the next version of Swift, so you shouldn't use it anymore.

It's always better to just write x += 1 instead of complex expressions with side effects.

like image 44
Sulthan Avatar answered Jan 18 '23 03:01

Sulthan