Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Basics Swift Operators Unary Operators

Al Hughes
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.