Bird
0
0

You want to print all numbers from a matched case up to 5 in a Swift switch. Which code correctly uses fallthrough to achieve this?

hard📝 Application Q15 of 15
Swift - Control Flow
You want to print all numbers from a matched case up to 5 in a Swift switch. Which code correctly uses fallthrough to achieve this?
let num = 3
switch num {
 case 1:
   print(1)
   fallthrough
 case 2:
   print(2)
   fallthrough
 case 3:
   print(3)
   fallthrough
 case 4:
   print(4)
   fallthrough
 case 5:
   print(5)
 default:
   print("Done")
}
AThis code prints 1 to 5 regardless of num.
BThis code prints only 3 when num is 3.
CThis code causes a compile error due to fallthrough in default.
DThis code prints 3, 4, 5 when num is 3.
Step-by-Step Solution
Solution:
  1. Step 1: Identify matched case and fallthrough chain

    When num is 3, case 3 matches and prints 3, then fallthrough continues to cases 4 and 5 printing 4 and 5.
  2. Step 2: Confirm output and default usage

    Default is not reached because cases 3 to 5 cover the fallthrough chain; no error occurs.
  3. Final Answer:

    This code prints 3, 4, 5 when num is 3. -> Option D
  4. Quick Check:

    Fallthrough chains print from matched case to end [OK]
Quick Trick: Use fallthrough in each case to print all following cases [OK]
Common Mistakes:
  • Expecting only matched case to print
  • Thinking default runs after fallthrough chain
  • Assuming compile error from fallthrough in default
  • Believing all cases print regardless of match

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes