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 Swift Operators Unary Operators

Al Hughes
seal-mask
.a{fill-rule:evenodd;}techdegree
Al Hughes
iOS Development Techdegree Student 469 Points

Can't make sense of this

Can someone explain to my why the below question would not result on Zero instead of -100

What is the value of totalScore?

var levelScore = 100 var totalScore = -levelScore

1 Answer

Shade Wilson
Shade Wilson
9,002 Points

You are confusing the -= operator and the negative (-) operator here. The value of totalScore would have been 0 if the code were written as follows:

var levelScore = 100 
var totalScore = 100
totalScore -= levelScore

This is because using -= here is the same as saying:

totalScore = totalScore - levelScore.

However, the question is stated differently:

var levelScore = 100 
var totalScore = -levelScore

Here the declaration of the variable totalScore is equivalent to the following:

var totalScore = -1 * levelScore

Thus, totalScore is simply -100.