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.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.