Bird
0
0

How can you simplify this Swift switch statement using compound cases?

hard📝 Application Q9 of 15
Swift - Control Flow

How can you simplify this Swift switch statement using compound cases?

switch number {
case 1:
    print("One")
case 2:
    print("Two")
case 3:
    print("Three")
case 4:
    print("Four")
case 5:
    print("Five")
default:
    print("Other")
}
ACombine cases 1, 2, 3 into one compound case
BUse if-else instead of switch
CCombine all cases into one compound case
DUse tuples in cases
Step-by-Step Solution
Solution:
  1. Step 1: Understand how compound cases simplify switch statements

    Compound cases group multiple values that execute the same code block. For example, cases 1, 2, 3 can be combined into case 1, 2, 3: if they share the same logic.
  2. Step 2: Evaluate the options

    Combine cases 1, 2, 3 into one compound case correctly describes using a compound case to combine cases 1, 2, 3. Other options either do not use compound cases or are incorrect approaches.
  3. Final Answer:

    Combine cases 1, 2, 3 into one compound case -> Option A
  4. Quick Check:

    Compound cases group values with same action [OK]
Quick Trick: Combine cases only if they share the same code block [OK]
Common Mistakes:
  • Combining cases with different outputs
  • Replacing switch with if-else unnecessarily
  • Using tuples incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes