Bird
0
0

You want to print numbers 1 through 3 using a Swift switch statement with fallthrough. Which code snippet correctly implements this?

hard📝 Application Q8 of 15
Swift - Control Flow
You want to print numbers 1 through 3 using a Swift switch statement with fallthrough. Which code snippet correctly implements this?
let number = 1
switch number {
 case 1:
   print("1")
   fallthrough
 case 2:
   print("2")
   fallthrough
 case 3:
   print("3")
 default:
   break
}
AThis code will only print "1" and stop
BThis code correctly prints 1, 2, and 3 when number is 1
CThis code causes a runtime error due to fallthrough misuse
DThis code prints 1 and 3 but skips 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand fallthrough chaining

    Using fallthrough in cases 1 and 2 causes execution to continue sequentially.
  2. Step 2: Execution flow

    When number is 1, it prints "1", then falls through to case 2 printing "2", then falls through to case 3 printing "3".
  3. Final Answer:

    This code correctly prints 1, 2, and 3 when number is 1 -> Option B
  4. Quick Check:

    fallthrough chains cases sequentially [OK]
Quick Trick: fallthrough chains execution to next case [OK]
Common Mistakes:
  • Expecting implicit fallthrough without keyword
  • Misplacing fallthrough causing skipped cases

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes