Bird
0
0

Identify the error in this Swift switch statement:

medium📝 Debug Q6 of 15
Swift - Control Flow
Identify the error in this Swift switch statement:
let x = 2
switch x {
 case 1:
  print("One")
  fallthrough
 case 3:
  print("Three")
}
ANo error; code runs fine
BMissing default case causes error
CFallthrough to a non-adjacent case is invalid
DFallthrough must be last statement in case
Step-by-Step Solution
Solution:
  1. Step 1: Exhaustiveness requirement

    Swift switch statements must be exhaustive, covering all possible input values or including a default case.
  2. Step 2: Identify the problem

    Cases cover only 1 and 3; no default means values like 2 (and others) are uncovered, causing compile error.
  3. Final Answer:

    Missing default case causes error -> Option B
  4. Quick Check:

    Non-exhaustive switch error [OK]
Quick Trick: Swift switch must be exhaustive or have default [OK]
Common Mistakes:
  • Thinking fallthrough to non-consecutive values is invalid
  • Assuming the code compiles and runs
  • Believing fallthrough must not be last statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes