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
switchmust 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
Inthas an enormous number of possible values, so you needdefaultas 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
switchends. You do not writebreakafter each case. (If you truly want to run the next case too, the keywordfallthroughdoes 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.
The draft
case 1...10:"Sapling", thencase 7, 14, 21:"Milestone!", thendefault.
Drills
Answer fast — trust the rule.
With the lesson's first switch, what prints for a streak of 3?
Why does a switch on an Int with cases 0, 1 and 2 only fail to compile?
After a matching case runs, what happens by default in Swift?
A case should do nothing for streak 0. What do you write?
Remember
switchmust cover every value; the first matching case runs, then stops.- Walk the doors from the top: specific cases before wide ranges.
- No
breakneeded after cases;defaultcatches the rest.
