Challenge: Calculate the Difference |

This is a companion discussion topic for the original entry at
1 Like

During this challenge, I wanted to try to do it without using multiplication. (i did the course a year ago with iOS 13, and wanted to go through it again to see the differences which has been great!)
I dug into the Int area of the Developer Documentation and found negate() in the “Performing Calculations” section. I came up with this:

func points(sliderValue: Int) → Int {
var difference: Int = - sliderValue
if difference < 0 {
var awardedPoints: Int = 100 - difference
return awardedPoints

It runs, and does the expected calculations, which made me really happy. Would this be something y’all would recommend against doing for this app, or is it just another solution?

@jnubz That’s a cool idea to try the course again to see what’s changed - hopefully you see a lot changed this year! :]

And that’s great you tried some creativity in your solution by trying out negate! That’s definitely a fine solution, and if you keep watching in this course I’ll show you another one that’s even fewer lines of code using abs.

When you’re developing apps, from a high level point of view the most important part is that your code works without bugs (which applies to any of these solutions, including yours)!

Once you’ve got that down, you can begin to optimize for things like fewer lines of code, readability, clean architecture, etc. And that often can be a matter of debate between developers on what’s best :]

1 Like

Thanks Ray! So far it’s been great to redo the course with all of the improvements that have been added in Swift and SwiftUI from iOS 13 to 14. I did appreciate that abs made it even more concise.

Thanks for the response.

1 Like

my solution was simply use absolute

    func points(sliderValue: Int) -> Int {
        return 100 - abs(target - sliderValue)