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

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: 24. Challenge: How to Calculate the Difference Next episode: 26. Challenge: Calculate the Difference

This video was last updated on Jan 11 2022

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.