Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: Coding in Swift

25. If / Else Statements

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 24. Challenge: How to Calculate the Difference Next episode: 26. Challenge: Calculate the Difference
Transcript: 25. If / Else Statements

Let’s implement the algorithm we just designed to calculate the difference between the slider and the target value in Swift.

Along the way, you’ll learn about an important new construct in Swift development: the if else statement. Let’s dive right in.

Go to points(sliderValue:), explain if statements

if something is true {
  then do this
} else if something else is true {
  then do that instead
} else {
  do something when neither of the above are true
}

Full implementation

func points(sliderValue: Int) -> Int {
  var difference: Int
  if sliderValue > self.target {
    difference = sliderValue - self.target
  } else if self.target > sliderValue {
    difference = self.target - sliderValue
  } else {
    difference = 0
  }
  var awardedPoints: Int = 100 - difference
  return awardedPoints
}

Cmd-U to run tests, show it works.

Then build and run. Show it working in the actual game.