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

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 25. If / Else Statements Next episode: 27. Variables & Constants
Transcript: 26. Challenge: Calculate the Difference

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 = - sliderValue
  if difference < 0 {
    difference = difference * -1
    // or difference *= -1
    // or difference = -difference
  var awardedPoints: Int = 100 - difference
  return awardedPoints