Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Basics (retired) Operators Unary Operators

Lawrence Yeo
Lawrence Yeo
3,236 Points

Postfix -- Decrements Confusing Me

var levelScore = 0 // 0

levelScore-- // 0

levelScore // -1

var totalScore = levelScore-- // -1

totalScore // -1 -> Shouldn't this value be -2? In the previous line of code, it looks like levelScore, which was previously assigned a value of -1, was decremented by 1. Shouldn't that make it -2, or the same value that is assigned to levelScore?

levelScore // -2

Thanks!

*disclaimer: I'm a newbie but I found apple's way of describing it pretty clear. I've cut and paste their explanation for the increment operator but you can use the same reasoning for the decrement operator:

var a = 0 let b = ++a // a and b are now both equal to 1 let c = a++ // a is now equal to 2, but c has been set to the pre-increment value of 1

In the example above, let b = ++a increments a before returning its value. This is why both a and b are equal to the new value of 1.

However, let c = a++ increments a after returning its value. This means that c gets the old value of 1, and a is then updated to equal 2.

Unless you need the specific behavior of i++, it is recommended that you use ++i and --i in all cases, because they have the typical expected behavior of modifying i and returning the result.

Jorge Solana
Jorge Solana
6,064 Points

What you are doing in this line is: var totalScore = levelScore-- // -1

Assign the variable totalScore the value of the variable levelScore, which is -1 at that point. Then you decrease the value of levelScore. That way totalScore equals -1 and levelScore equals -2.

This works like precedent operators. If the operand "++"/"--" is located in front of a variable, that math comes first, but if it is located behind, you first assign the value and then increment/decrease the variable value.

Hope it helps.