Bird
0
0

What will happen if you run this Swift code?

medium📝 Predict Output Q5 of 15
Swift - Loops
What will happen if you run this Swift code?
var numbers = [1, 2, 3]
for number in numbers {
  numbers.append(number + 3)
  print(number)
}
AInfinite loop printing numbers
BPrints 1 2 3 and then stops
CCompile-time error due to modifying collection during iteration
DRuntime crash due to array modification
Step-by-Step Solution
Solution:
  1. Step 1: Identify mutation inside loop

    The code tries to append to 'numbers' while looping over it.
  2. Step 2: Recall Swift safety rules

    Swift disallows modifying a collection during iteration and shows a compile-time error.
  3. Final Answer:

    Compile-time error due to modifying collection during iteration -> Option C
  4. Quick Check:

    Modifying collection in loop = Compile-time error [OK]
Quick Trick: Cannot change collection while looping in Swift [OK]
Common Mistakes:
  • Expecting infinite loop
  • Assuming runtime crash instead of compile error
  • Thinking it prints all numbers including appended ones

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes