Introduction
Stride lets you count numbers with a custom step size easily. It helps when you want to skip numbers or count in jumps.
Stride lets you count numbers with a custom step size easily. It helps when you want to skip numbers or count in jumps.
stride(from: start, to: end, by: step) stride(from: start, through: end, by: step)
from is where counting starts.
to stops before this number, through includes this number.
for number in stride(from: 0, to: 10, by: 2) { print(number) }
for number in stride(from: 1, through: 5, by: 1) { print(number) }
for number in stride(from: 10, to: 0, by: -3) { print(number) }
This program shows counting up from 0 to 15 by 3 steps, then counting down from 20 to 0 by 4 steps.
import Foundation print("Counting up by 3:") for number in stride(from: 0, to: 15, by: 3) { print(number) } print("Counting down by 4:") for number in stride(from: 20, through: 0, by: -4) { print(number) }
Use to when you want to stop before the end number.
Use through when you want to include the end number.
Negative by values let you count backwards.
Stride helps count numbers with custom steps easily.
Use to to exclude the end, through to include it.
Steps can be positive or negative for counting up or down.
stride(from: 1, to: 10, by: 2) do?from: 1 as the start, to: 10 as the end (exclusive), and by: 2 as the step size.through.stride(from: 10, through: 2, by: -2) matches counting down with inclusion of 2.for i in stride(from: 0, to: 5, by: 2) {
print(i)
}for i in stride(from: 1, through: 10, by: 0) {
print(i)
}stride(from: 1, through: 15, by: 2) generates 1,3,5,...,15 including 15.if i > 5 prints only numbers greater than 5, i.e., 7,9,11,13,15.Pass the test and this pattern moves unknown