if, else if, and else choose one branch based on Boolean conditions.

Choose a branch

score
if_else.swift
Replay: real traced execution (multi-file project)
let score = 74
var band = "needs practice"

if score >= 90 {
    band = "excellent"
} else if score >= 70 {
    band = "steady"
} else {
    band = "needs practice"
}

print("score=\(score)")
print("band=\(band)")
let score = 58
var band = "needs practice"

if score >= 90 {
    band = "excellent"
} else if score >= 70 {
    band = "steady"
} else {
    band = "needs practice"
}

print("score=\(score)")
print("band=\(band)")
let score = 91
var band = "needs practice"

if score >= 90 {
    band = "excellent"
} else if score >= 70 {
    band = "steady"
} else {
    band = "needs practice"
}

print("score=\(score)")
print("band=\(band)")
  1. score ← 74, band ← needs practice

    1let score→ 74 = 74  //@score=91, 582var band→ needs practice = "needs practice"
  2. if score >= 70

    5    band = "excellent"6} else if score74 >= 70 {7    band = "steady"8} else {
  3. print("score=\(score)")

    12print("score=\(score74)")13print("band=\(bandsteady)")
    outputscore=74
    band=steady
  1. score ← 58, band ← needs practice

    1let score→ 58 = 582var band→ needs practice = "needs practice"
  2. print("score=\(score)")

    12print("score=\(score58)")13print("band=\(bandneeds practice)")
    outputscore=58
    band=needs practice
  1. score ← 91, band ← needs practice

    1let score→ 91 = 912var band→ needs practice = "needs practice"
  2. if score >= 90

    4if score91 >= 90 {5    band = "excellent"6} else if score >= 70 {
  3. print("score=\(score)")

    12print("score=\(score91)")13print("band=\(bandexcellent)")
    outputscore=91
    band=excellent

Choose the Band

  1. score starts at 74.
  2. The first check, score >= 90, is false.
  3. The next check, score >= 70, is true.
  4. band becomes steady. | Score | First matching branch | Band | | --- | --- | --- | | 91 | score >= 90 | excellent | | 74 | score >= 70 | steady | | 58 | else | needs practice |
branching An `if` chain tests conditions in order. Swift runs the first branch whose condition is true and skips the rest.

Exercise: if_else.swift

Use if, else if, and else to map a score to excellent, steady, or needs practice