0
0
Swiftprogramming~10 mins

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

Choose your learning style9 modes available
Concept Flow - For-in loop with ranges
Start
Set range start and end
Pick next number in range
Execute loop body with number
More numbers in range?
NoEnd
Yes
Pick next number in range
The loop picks each number from the range one by one and runs the code inside the loop for each number until all numbers are used.
Execution Sample
Swift
for i in 1...3 {
    print(i)
}
This code prints numbers 1, 2, and 3, one on each line.
Execution Table
Iterationi valueActionOutput
11Print i1
22Print i2
33Print i3
4-No more numbers in range-
💡 i reaches 3, next number does not exist, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
i-123-
Key Moments - 2 Insights
Why does the loop stop after printing 3?
Because the range 1...3 includes only numbers 1, 2, and 3. After 3, there are no more numbers, so the loop ends as shown in execution_table row 4.
What if we use 1..<3 instead of 1...3?
The range 1..<3 includes 1 and 2 but not 3. So the loop would run only twice, printing 1 and 2. This is a half-open range.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at iteration 2?
A1
B3
C2
D-
💡 Hint
Check the 'i value' column in the execution_table at iteration 2.
At which iteration does the loop stop because there are no more numbers?
A3
B4
C2
D1
💡 Hint
Look at the 'Action' column where it says 'No more numbers in range'.
If the range changes to 1..<3, how many times will the loop run?
A2 times
B3 times
C1 time
D4 times
💡 Hint
Recall that 1..<3 excludes 3, so it includes 1 and 2 only.
Concept Snapshot
for i in start...end {
    // code using i
}

- Runs loop from start to end including end
- i takes each number in the range
- Use ... for closed range (includes end)
- Use ..< for half-open range (excludes end)
Full Transcript
This visual execution shows how a for-in loop with a range works in Swift. The loop variable i takes each number from the range 1 to 3, including 3. Each iteration prints the current value of i. The loop stops after reaching the last number in the range. The execution table tracks each iteration, the value of i, the action taken, and the output printed. The variable tracker shows how i changes over time. Key moments clarify why the loop stops and the difference between closed and half-open ranges. The quiz tests understanding of the loop variable values and loop termination conditions.