How to Use stride() in a for Loop in Swift
To repeat code execution (looping) in Swift, you can use the for-in, while, and repeat-while statements.
The basics of the for-in loop in Swift are explained in Swift for Loop.
To loop over a range of numbers using a for-in statement, you can use range operators such as ....
For example, if you want to loop from 1 to 5, you can write it like this:
for i in 1...5 {
print("i = \(i)")
}
[Execution Result]
i = 1
i = 2
i = 3
i = 4
i = 5
In this case, the value of i increased by 1 with each loop iteration. However, by using the stride() function, you can control the loop more flexibly.
The stride() function has two forms. The first one, stride(from:to:by:), is used like this:
for variable in stride(from: startValue, to: endValue, by: step) {
// code to repeat
}
The from parameter specifies the starting value of the loop.
The loop runs up to but does not include the end value.
The by parameter specifies the step value added at each iteration. If a negative value is set, the value decreases with each loop.
Depending on the values of from and by, if you want the loop to include the end value when it exactly matches, you can use stride(from:through:by:) instead.
for variable in stride(from: startValue, through: endValue, by: step) {
// code to repeat
}
The behavior is the same as stride(from:to:by:) except that the end value is included.
For example, if you want to loop from 0 up to but not including 5, in steps of 0.5, you can do the following:
for i in stride(from: 0, to: 5, by: 0.5) {
print("i = \(i)")
}
The result shows that the value increases by 0.5 each iteration, and the print statement runs 10 times. Notice that the loop exits when i reaches 5.
i = 0.0
i = 0.5
i = 1.0
i = 1.5
i = 2.0
i = 2.5
i = 3.0
i = 3.5
i = 4.0
i = 4.5
If you want to include 5 in the loop, change to to through.
for i in stride(from: 0, through: 5, by: 0.5) {
print("i = \(i)")
}
The result shows that the loop also executes when i = 5:
i = 0.0
i = 0.5
i = 1.0
i = 1.5
i = 2.0
i = 2.5
i = 3.0
i = 3.5
i = 4.0
i = 4.5
i = 5.0
That's how you can use stride() with a for loop in Swift.