Updated 3 June 2024
We’ll explore how to utilize the Stride in Swift using for loop to iterate over ranges with custom step values.
The ‘for’ loop is a powerful tool for iterating over a range of numbers with a specific increment.
The ‘stride’ function provides an efficient way to accomplish this.
Using ‘stride’ is like using for loop in C language.
1 2 3 |
for (int i = 0; i < 100; i++){ print(i) // it will prints value from 0 to 100 } |
In Swift, you can use for in loop as below example:-
1 |
for i in 0..<100 {<br> print(i) //prints value from 0 to 99<br>} |
The ‘stride’ function provides a more elegant solution for iterating over ranges with custom step values.
There are two ways to use stride.
stride(from:to:by:)
Using stride(from:to:by:) will not include the value of last value that you will provide on the “to” parameter.
“by” parameter takes the amount to step by with each iteration.
1 |
for i in stride(from: 0, to: 100, by: 1) {<br> print(i) // prints from 0 to 99 and by is increment value i.e. 1<br>} |
stride(from:through:by:)
Using stride(from:through:by:) will include the value of last value that you will provide on the “through” parameter.
“by” parameter takes the amount to step by with each iteration.
1 |
for i in stride(from: 0, through: 100, by: 1) {<br> print(i) // prints from 0 to 100 and by is increment value i.e. 1<br>} |
Using the ‘stride’ function within a ‘for’ loop in Swift allows for efficient iteration over ranges with custom step values. Whether you’re working with inclusive or exclusive ranges, ‘stride’ provides a clean and concise syntax for achieving the desired result.
You can continue your learning journey with more interesting topics and technologies with the Mobikul Blog.
You can also check our Flutter Development Services.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.