0
0
Swiftprogramming~10 mins

Array iteration and enumerated in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array iteration and enumerated
Start with array
Begin iteration
Get index and element
Use index and element
Move to next element
More elements?
YesRepeat
No
End iteration
This flow shows how Swift goes through each item in an array, getting both the position (index) and the value (element) to use inside the loop.
Execution Sample
Swift
let fruits = ["Apple", "Banana", "Cherry"]
for (index, fruit) in fruits.enumerated() {
    print("\(index): \(fruit)")
}
This code loops over the fruits array, printing each fruit with its index.
Execution Table
StepindexfruitActionOutput
10"Apple"Print index and fruit0: Apple
21"Banana"Print index and fruit1: Banana
32"Cherry"Print index and fruit2: Cherry
4--No more elements, loop ends-
💡 After index 2, no more elements in array, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
index-012-
fruit-"Apple""Banana""Cherry"-
Key Moments - 3 Insights
Why does the index start at 0 instead of 1?
In Swift arrays, counting starts at 0 by design. The execution_table shows index starting at 0 in step 1, which is normal for array positions.
What does enumerated() do exactly?
enumerated() pairs each element with its index. The execution_table rows show both index and fruit together, proving enumerated() gives both.
What happens if the array is empty?
If the array is empty, the loop body never runs. The exit_note explains the loop ends immediately when no elements exist.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the fruit at step 2?
A"Banana"
B"Apple"
C"Cherry"
DNo fruit
💡 Hint
Check the 'fruit' column in row with Step 2 in execution_table
At which step does the loop stop because there are no more elements?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the exit_note and the last row in execution_table
If the array had 4 fruits, how many steps would the execution_table have before stopping?
A4 steps
B3 steps
C5 steps
D6 steps
💡 Hint
Notice the pattern: number of elements + 1 exit step in execution_table
Concept Snapshot
Swift array iteration with enumerated():
- Use for (index, element) in array.enumerated() to get index and value
- Index starts at 0
- Loop runs once per element
- Loop ends when no more elements
- Useful for position-aware processing
Full Transcript
This visual shows how Swift loops over an array using enumerated(). The loop starts with index 0 and the first fruit, then moves to the next index and fruit, printing each pair. When all fruits are processed, the loop ends. The variable tracker shows how index and fruit change each step. Common confusions include why index starts at 0 and what enumerated() does. The quiz checks understanding of the steps and loop end.