Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Control Flow  ›  Lesson

switch and case

switch / case 12 minA switch compares a value against cases from top to bottom, runs only the first match without falling through, and must be exhaustive, usually with a default case.

switch and case

Sprout gives each streak length its own badge: nothing at 0, "Seedling" for the first week, a special badge on days 7, 14 and 21, and "Tree" beyond. A long if/else if chain can do it, but switch reads like the table in the design notes.

The rule

switch must cover every value; the first matching case runs, then stops.

let streak = 14

switch streak {
case 0:
    print("No badge yet")
case 1...6:
    print("Seedling")
case 7, 14, 21:
    print("Milestone!")
default:
    print("Tree")
}
// prints "Milestone!"

The rules:

  • Exhaustive. Every possible value must match some case. An Int has an enormous number of possible values, so you need default as a catch-all.
  • First match wins. Swift checks cases top to bottom and runs only the first that matches.
  • No falling through. When a case finishes, the whole switch ends. You do not write break after each case. (If you truly want to run the next case too, the keyword fallthrough does it.)
  • Every case needs a statement. For "do nothing", write break.

Cases can match more than single values:

  • several values: case 7, 14, 21:
  • ranges: case 1...6:
  • extra conditions: case let n where n > 100:
  • strings and, later, enums: case "Read":

Like if, a switch can produce a value:

let badge = switch streak {
case 0: "None"
case 1...6: "Seedling"
default: "Tree"
}

The shortcut

Read a switch like a list of doors, tried from the top. Take the value, walk down, and go through the first door it fits. Nothing after that door matters.

Badge for a 7-day streak, draft twoStep 1 of 4
  1. The draft

    case 1...10: "Sapling", then case 7, 14, 21: "Milestone!", then default.

Drills

Answer fast — trust the rule.

quick drill

With the lesson's first switch, what prints for a streak of 3?

quick drill

Why does a switch on an Int with cases 0, 1 and 2 only fail to compile?

quick drill

After a matching case runs, what happens by default in Swift?

quick drill

A case should do nothing for streak 0. What do you write?

Remember

  • switch must cover every value; the first matching case runs, then stops.
  • Walk the doors from the top: specific cases before wide ranges.
  • No break needed after cases; default catches the rest.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWrite the badge switch

Write a switch on streak that gives 'None' for 0, 'Milestone' for 7, 14 or 21, 'Seedling' for 1 to 13, and 'Tree' for anything larger. Explain why the case order matters and why default is needed.