Leave a rating/review
In the previous challenge, I mentioned that there’s another way to calculate the difference that requires fewer lines of code - and that’s the subject of this challenge.
The new algorithm looks like this:
- First, subtract the target value from the slider’s value.
- Then, if the result is a negative number, then multiply it by -1 to make it a positive number.
At this point, pause the video and try changing the difference calculation to this new algorithm. Then keep watching to compare your work to my solution.
That’s it - good luck.
All right, I’m going to delete our old If Else statements here. And instead, we’re just going to say the difference equals target minus sliderValue.
func points(sliderValue: Int) -> Int {
var difference: Int = target - sliderValue
Now this might be negative, right? Because what if target is 50 and sliderValue is 55, that would be negative five.
So we’re going to say, If difference is less than zero, then we’re going to say difference equals difference times negative one.
if difference < 0 {
difference = difference * -1
// or difference *= -1
// or difference = -difference
}
So it’s like a negative five difference equals difference negative five times negative one, which would be a positive five.
There’s a couple of shortcuts to doing this line in Swift, and I’ll put two of them in comments here.
You can make a comment in your code with two forward slashes. Any code after this on this line won’t run, it’s just for your reference!
So, instead of this, we could say difference times equals negative one.
difference = difference * -1
// or difference *= -1
These two lines are exactly the same, the second one is just a shortcut way to type it because I haven’t had to type difference twice.
And actually there’s another shortcut you can use here, you can say difference equals negative difference.
difference = difference * -1
// or difference *= -1
// or difference = -difference
All of those, they all work the same. I’m just going to leave it as this first one for now and delete the comments. You are welcome to keep them for your own reference!
All right, so I’m going to hit Command + U first of all, this is one of the benefits of unit tests. We can make sure we didn’t break anything. So if our unit tests pass, our code should be good.
I switched over to the test navigator, we got greens everywhere. So that’s looking good and I’m just going to run the app just to manually test as well.
Give it my best guess, and that looks right! Nice work.