0
0
Swiftprogramming~10 mins

Switch with compound cases in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch with compound cases
Start: value to check
Switch statement begins
Check first case
Execute case
End switch
Default case
Execute default
End switch
The switch checks the value against each case, including compound cases separated by commas, and executes the matching case block.
Execution Sample
Swift
let letter = "a"
switch letter {
case "a", "e", "i", "o", "u":
    print("Vowel")
default:
    print("Consonant")
}
This code checks if the letter is a vowel using a switch with compound cases.
Execution Table
StepCondition CheckedResultBranch TakenOutput
1letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u"True (letter is "a")case "a", "e", "i", "o", "u"Vowel
2Switch ends after matching caseN/AExit switchN/A
💡 Matching case found at step 1, switch exits after executing that case.
Variable Tracker
VariableStartAfter Step 1Final
letter"a""a""a"
Key Moments - 2 Insights
Why does the switch not check other cases after finding a match?
Because in Swift, once a matching case is found, the switch exits immediately as shown in execution_table step 2.
How do compound cases work in the switch?
Compound cases use commas to list multiple values in one case, so if the value matches any of them, that case runs (see execution_table step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 1?
AError
BConsonant
CVowel
DNo output
💡 Hint
Check the 'Output' column in execution_table row 1.
At which step does the switch stop checking cases?
AStep 1
BStep 2
CAfter default case
DNever stops
💡 Hint
Look at the 'Branch Taken' and 'Exit switch' note in execution_table step 2.
If letter was "b", what case would run?
Adefault
Bcase "a", "e", "i", "o", "u"
CNo case runs
DError
💡 Hint
If no compound case matches, switch runs the default case.
Concept Snapshot
switch value {
  case val1, val2, val3:
    // runs if value matches any listed
  default:
    // runs if no case matches
}
- Compound cases use commas to check multiple values
- Switch exits after first match
- Default handles unmatched values
Full Transcript
This example shows how a Swift switch statement uses compound cases separated by commas to check if a value matches any of several options. The switch checks each case in order. When it finds a match, it runs that case's code and then exits the switch immediately. If no cases match, the default case runs. Here, the letter "a" matches the first compound case, so "Vowel" is printed and the switch ends.