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

Liam Hayes
seal-mask
.a{fill-rule:evenodd;}techdegree
Liam Hayes
Full Stack JavaScript Techdegree Student 13,116 Points

Can the - operator be used to negate stuff in Swift?

Hi guys,

Check out this code from the very first course in the iOS track. This is from Beginner iOS Development > Course 1 Swift Basics > Part 3 Swift Operators > very last episode Unary Operators Quiz

What is the value of totalScore?

var levelScore = 100

var totalScore = -levelScore

The correct answer is totalScore = -100

So I guess this means that the - operator works as if you're multiplying by -1?

Check this out though, it doesn't seem to work every time

I tried it in my compiler like this

var something = -(100 * 10)

And that did NOT work. It did NOT give me -1000

So does this -1 multiplication only work in very specific cases? Anything else I should know about it?

Thank you guys :)

1 Answer

Stuart Wright
Stuart Wright
41,119 Points

I'm not at my Mac right now so just tested in an online Swift playground, was really surprised to see that your example didn't work - I would have assumed it did. I don't know Swift well enough to answer your question, but interestingly this compiles fine:

var x = 100
var y = 10
var something = -(x * y)

And the variable something is -1000 as expected. Strange.