0
0
Swiftprogramming~10 mins

For-in loop with collections in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For-in loop with collections
Start with collection
Pick first item
Execute loop body with item
More items?
NoExit loop
Yes
Pick next item
Back to Execute loop body
The loop picks each item from the collection one by one and runs the code inside the loop for each item until all items are done.
Execution Sample
Swift
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
    print(fruit)
}
This code goes through each fruit in the list and prints its name.
Execution Table
Iterationfruit valueActionOutput
1"Apple"Print fruitApple
2"Banana"Print fruitBanana
3"Cherry"Print fruitCherry
--No more items, exit loop-
💡 All items in the collection have been processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
fruitnil"Apple""Banana""Cherry"nil
Key Moments - 2 Insights
Why does the loop variable 'fruit' change each time?
Because the loop picks the next item from the collection each iteration, as shown in the execution_table rows 1 to 3.
Does the original collection 'fruits' change during the loop?
No, the collection stays the same; only the loop variable 'fruit' changes to each item, as seen in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'fruit' in iteration 2?
A"Banana"
B"Apple"
C"Cherry"
Dnil
💡 Hint
Check the 'fruit value' column in row 2 of execution_table.
At which iteration does the loop finish processing all items?
AAfter iteration 2
BAfter iteration 3
CAfter iteration 1
DNever ends
💡 Hint
Look at the exit_note and the last iteration row in execution_table.
If the collection had 4 items, how many times would the loop run?
A3 times
B5 times
C4 times
DDepends on the code inside the loop
💡 Hint
The loop runs once for each item in the collection, as shown in the concept_flow.
Concept Snapshot
For-in loop syntax:
for item in collection {
    // code using item
}

Behavior:
- Loops over each item in the collection
- 'item' changes each iteration
- Loop ends after last item

Key rule: The collection is not changed by the loop.
Full Transcript
This visual shows how a for-in loop works with collections in Swift. The loop starts by picking the first item from the collection. Then it runs the code inside the loop using that item. After that, it checks if there are more items. If yes, it picks the next item and repeats. If no, it stops. The variable 'fruit' holds the current item and changes each time. The original collection stays the same. The loop runs once for each item in the collection.