Bird
0
0

Identify the error in this Swift switch statement using where clauses:

medium📝 Debug Q14 of 15
Swift - Control Flow

Identify the error in this Swift switch statement using where clauses:

let score = 85
switch score {
case let x where x > 90:
    print("Excellent")
case let x where x >= 80:
    print("Good")
case let x where x >= 70:
    print("Average")
case _:
    print("Poor")
}
AUsing let binding is not allowed with where.
BMissing default case for unmatched values.
CIncorrect syntax for where clause.
DThe cases overlap and order causes wrong matching.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze case conditions and order

    The cases check if score > 90, then >= 80, then >= 70. Since 85 >= 80 and also >= 70, the second case matches first.
  2. Step 2: Understand overlapping conditions effect

    Because cases overlap, order matters. If order was different, output might change. This can cause confusion or wrong matching.
  3. Final Answer:

    The cases overlap and order causes wrong matching. -> Option D
  4. Quick Check:

    Overlapping where clauses need careful order [OK]
Quick Trick: Order cases from most specific to least specific [OK]
Common Mistakes:
  • Ignoring overlapping conditions
  • Assuming default case is mandatory
  • Thinking let binding disallowed with where

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes