In a Swift for loop, you can use the stride
method to increment by more than one. The stride
method takes three arguments: the starting value, the ending value, and the amount to increment by. Here’s an example:
for i in stride(from: 0, to: 10, by: 2) { print(i) }
In this example, the loop starts at 0 and increments by 2 until it reaches 10. The output of this loop will be:
0 2 4 6 8
You can also use the stride
method with the through
argument to include the ending value in the loop:
for i in stride(from: 0, through: 10, by: 2) { print(i) }
In this example, the loop starts at 0 and increments by 2 until it reaches 10, including 10 in the loop. The output of this loop will be:
0 2 4 6 8 10
Using the stride
method is a simple and efficient way to increment by more than one in a Swift for loop.