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 value = 10
switch value {
 case 5: print("Five")
 case 10: print("Ten")
}
AMissing default case causes compile error.
BNo error, code is correct.
CSwitch variable type is incorrect.
DCases overlap causing ambiguity.
Step-by-Step Solution
Solution:
  1. Step 1: Check switch coverage

    Switch statements in Swift do not require a default case if the variable's type is not an enum and the cases cover all intended values.
  2. Step 2: Analyze given cases

    Since the variable is an Int and the switch covers cases 5 and 10, no compile error occurs; the switch is valid but not exhaustive, which is allowed for non-enum types.
  3. Final Answer:

    No error, code is correct. -> Option B
  4. Quick Check:

    Switch without default on Int type = Valid code [OK]
Quick Trick: Default is not mandatory for non-enum types [OK]
Common Mistakes:
  • Assuming no default is always required
  • Thinking cases overlap here
  • Believing variable type is wrong

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes