Reputation: 5061
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?
now with println
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.
Upvotes: 2
Views: 75
Reputation: 1927
++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 */
Upvotes: 0
Reputation: 16855
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.
Upvotes: 6