About this episode
See versions
See forum comments
Mark complete
Previous episode: 24. Challenge: How to Calculate the Difference
Next episode: 26. Challenge: Calculate the Difference
Leave a rating/review
This video If / Else Statements 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.