stride() in swift — to loop over a range

Abhimuralidharan
2 min readMay 31, 2017

Read the apple docs here and here.

We all are familiar with the classic for loop in c language. Just have a look at the code below.

for (int i = 0; i < 10; i += 1){
print(i) // prints from 0 to 9
}

The above code will loop 10 times from i equal to zero to 9. If i becomes 10, then the control flow will come out of the loop. So we can say that the code looped from 0 to 10 (exclusive), printing out numbers from 0,1,2, . . . 9.

The c- style for loops are no longer supported in swift 3. The for loop that we have in swift today will not allow us to do the functionality explained above.

Swift has a replacement in the stride() function, which lets you move from one value to another using any increment and even lets you specify whether the upper bound is exclusive or inclusive.

Swift has two types of stride functions:

‣ stride(from:to:by:)

stride(from:to:by:) counts from the start point up to by excluding the to parameter. So, the above for-loop can be written in swift using stride as:

for i in stride(from: 0, to: 10, by: 1) {
print(i) // prints from 0 to 9
}

‣ stride(from:through:by:)

stride(from:through:by:) counts from the start point up to by including the through parameter.

for i in stride(from: 0

--

--