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, through: 10, by: 1) {
print(i) // prints 0 to 10
}

Skimming through the apple docs:

The above two methods are generic methods with type constraints which confirms to Strideable protocol.

Strideable: Conforming types are notionally continuous, one-dimensional values that can be offset and measured.

Declaration for stride(from:to:by:) — apple docs

func stride<T>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> where T : Strideable

Declaration for stride(from:through:by:) — apple docs

func stride<T>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> where T : Strideable

NOTE: Alternatively you may also use for-in loop using open and closed ranges to achieve the same. The limitation is that , the binary operator ‘…’ cannot be applied for decimal point numbers. The closed and open ranges should conform to protocol ‘Sequence’.

for i in 0...10 { // for both 0 and 10 included.print(i) // prints 0 to 10}
for i in 0..<10 { // for 0 to 9 .
print(i) // prints 0 to 9}for i in 0.1..<10.1 { // error 'ClosedRange<Double>' does not conform to protocol 'Sequence'print(i) }

If you enjoyed reading this post and found it useful, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

Thanks!!

--

--

Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨