2

The image is a screenshot from a Swift playground -> code on the left, log (if you can call it that) on the right.

I suppose what I expected to happen was that line 8 would result in 1 because, you know, 0 + 1 = 1

Can anyone explain what is happening here?

enter image description here

now with println

enter image description here

p.s. before you say anything about it, I understand semi-colons are useless now, it's habit since i'm just today deciding to learn Swift coming from Obj-C.

jscs
  • 63,694
  • 13
  • 151
  • 195
esreli
  • 4,993
  • 2
  • 26
  • 40

2 Answers2

6

From here:What is the difference between ++i and i++?

  • ++i will increment the value of i, and then return the incremented value.

  • i++ will increment the value of i, but return the original value that i held before being incremented.

The playground prints the return value of that line, and in the i++ case, it will return i's original value and so prints it, then increments it.

Community
  • 1
  • 1
Jack
  • 16,677
  • 8
  • 47
  • 51
  • 3
    This is not specific to swift, this is true of every language I know. – shim Dec 04 '14 at 18:42
  • 1
    @achi actually, this is a pretty standard syntax that is in C as well as several other languages. – Jack Dec 04 '14 at 18:43
0

++i Known as the pre-increment operator. If used in a statement will increment the value of i by 1, and then use the incremented value to evaluate the statement.

int i = 0;
println(++i); /* output 1 */ 
println(i); /* output 1 */

b++ Known as the post-increment operator. If used in a statement will use the current value of b, and once the statement is evaluated, it then increments the value of b by 1.

int b = 0;
println(b++); /* output 0 */
println(b); /* output 1 */

Note that when you use the pre and post increment operator are used by themselves the behave the same way

int y = 0;
int z = 0; 
++y; 
z++;
println(y); /* output 1 */
println(z); /* output 1 */
Kalenda
  • 1,847
  • 14
  • 15