Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 Swift 5.5, iOS 15, Xcode 13

Part 3: Coding in Swift

26. Challenge: Calculate the Difference

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 25. If / Else Statements Next episode: 27. Variables & Constants

This video was last updated on Jan 11 2022

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.

Alright that’s it - good luck.

func points(sliderValue: Int) -> Int {
  var difference: Int = self.target - sliderValue
  if difference < 0 {
    difference = difference * -1
    // or difference *= -1
    // or difference = -difference
  }
  var awardedPoints: Int = 100 - difference
  return awardedPoints
}