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 trialRos Zunra
767 PointsHI guys, I still don't get how the postfix works
Hello everyone, here's my coding
var levelScore = 0 // 0
levelScore++ // 0
levelScore // 1
//OK, the increment appears in the next line
var totalScore = 0 // 0
/----- confusion starts -----/
totalScore = levelScore++ // 1
// Now I read this line as (totalScore) values 1 because (levelScore) values 1, the (++) hasn't worked yet.
levelScore // 2
totalScore // 1
/----- confusion ends -----/
totalScore = levelScore++ // 1
Why putting (++) in this line, when (++) only affect (levelScore) but not (totalScore)?
I can see that 1 added to the value of (levelScore) in the next line, which seems to be equal to
levelScore++ // 1
levelScore // 2
But since the value of (totalScore) won't change, what does it mean putting (++) in (totalScore = levelScore ++)?
Thank you guys!
2 Answers
Max Hirsh
16,773 PointsMy best guess is that it's one of swifts quirks/design features, so where in other programming languages you could iterate and assign to a variable in one line, but in swift you need to do it in two. I've run into this before with lengthy math formulas that I had to break into multiple steps.
Max Hirsh
16,773 PointsHey Lauren, thank you for your comment. The quirk I was talking about was not the existence of postfixes/prefixes, I was referring to how swift seems to only apply the postfixes after reading through a line of code, assigning variables and so on. If you look at the details in Ros's code example, you'll see that Swift is doing some weird things that I don't think happen in Java or most other languages that use pre/post-fixes.
Ros Zunra
767 PointsRos Zunra
767 PointsThanks!
Lauren Hibbs
1,872 PointsLauren Hibbs
1,872 PointsThis isn't a quirk of Swift. Prefix and postfix operators exist in many other programming languages.
Postfix means "after", hence "post". You first complete your operation, or pass it to a function, and then increment your variable. For example var i = 0; println(i++) // prints out 0, although the value of i is now 1
Prefix means "before" and has "pre" in it. The variable is incremented and then the operation or function is completed. var i =0; println(++i) // prints out 1, and the value of i is 1
Using prefix allows you to iterate and assign to a variable in one line. I don't have any experience in Swift, but I have a lot in Java. Hope this helps.