0
0
Swiftprogramming~10 mins

Stride for custom step in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Stride for custom step
Start at 'from'
Check: current < to?
NoEXIT
Yes
Execute loop body
Add 'by' to current
Back to Check
This flow shows how stride starts from a value, checks if it is less than the end, runs the loop body, then adds the step size before repeating.
Execution Sample
Swift
for i in stride(from: 0, to: 10, by: 3) {
    print(i)
}
This code prints numbers from 0 up to (but not including) 10, stepping by 3 each time.
Execution Table
Iterationi (current value)Condition (i < 10)ActionOutput
10trueprint(i), i = i + 30
23trueprint(i), i = i + 33
36trueprint(i), i = i + 36
49trueprint(i), i = i + 39
512falseexit loop
💡 i reaches 12, condition 12 < 10 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
i03691212
Key Moments - 3 Insights
Why does the loop stop before printing 12?
Because the condition i < 10 becomes false when i is 12, so the loop exits before printing 12, as shown in execution_table row 5.
What does the 'by' parameter control?
The 'by' parameter controls how much i increases each time, here it adds 3 after each print, as seen in variable_tracker.
Why is the last printed value 9 and not 10?
Because stride uses 'to' which excludes the end value 10, so it stops before reaching 10, shown in the condition checks in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at iteration 3?
A6
B9
C3
D12
💡 Hint
Check the 'i (current value)' column at iteration 3 in the execution_table.
At which iteration does the condition i < 10 become false?
A4
B5
C3
D2
💡 Hint
Look at the 'Condition (i < 10)' column in execution_table where it becomes false.
If the 'by' value changed to 4, what would be the output at iteration 2?
A6
B3
C4
D8
💡 Hint
With 'by' = 4, i increases by 4 each iteration starting from 0, so after first iteration i is 4.
Concept Snapshot
Stride syntax: stride(from: start, to: end, by: step)
Loops from start up to but not including end
Increments by step each time
Stops when current value >= end
Useful for custom step loops
Full Transcript
This visual execution shows how Swift's stride function works with a custom step. Starting at 0, it checks if the current value is less than 10. If yes, it prints the value, then adds 3. This repeats until the value reaches 12, which fails the condition and stops the loop. The variable i changes from 0 to 3, 6, 9, then 12. The loop prints 0, 3, 6, and 9. The step size controls how much i increases each time. The loop excludes the end value 10 because 'to' is used. This helps understand how stride controls loop steps and limits.