stride() in swift — to loop over a range

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

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.

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
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!!

--

--

iOS and tvOS developer, dreamer, photographer 🤨

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhimuralidharan

Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨