Bird
0
0

What is wrong with this enum and switch code?

medium📝 Debug Q14 of 15
iOS Swift - Swift Language Essentials
What is wrong with this enum and switch code?
enum Direction {
  case up(Int)
  case down(Int)
}

let dir = Direction.up(10)
switch dir {
case .up:
  print("Going up")
case .down:
  print("Going down")
}
ASwitch cases must extract associated values with let
BEnum cases cannot have associated values
CVariable dir is not initialized correctly
DSwitch must have a default case
Step-by-Step Solution
Solution:
  1. Step 1: Check enum cases with associated values

    Cases up and down have Int associated values.
  2. Step 2: Analyze switch cases

    Switch cases .up and .down do not extract the Int value with let, causing a compile error.
  3. Final Answer:

    Switch cases must extract associated values with let -> Option A
  4. Quick Check:

    Extract associated values in switch cases [OK]
Quick Trick: Always use let to get associated values in switch [OK]
Common Mistakes:
  • Ignoring associated values in switch
  • Thinking default case is mandatory
  • Wrong enum initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes