Stride in Swift
Using Stride in swift is like using for loop in C – language and in C – the language you use for loop like:-
1 2 3 |
for (int i = 0; i < 100; i++){ print(i) // it will prints value from 0 to 100 } |
And in Swift, you can use only for each loop example:-
1 2 3 |
for i in 0..<100 { print(i) prints value from 0 to 99 } |
When you want to increment value of like i= i+2 or i = i +3 so it’s not possible directly to increment the value of i in swift for each loop so you have to apply your own logic to increment the value of i, like in C language. By stride method you can increment value stride contains two methods : –
-
stride(from:to:by:)
- stride(from:through:by:)
Using stride(from:to:by:) it will not include the value of last value that you will give to: field and set by: field value that is incremented value example:-
1 2 3 |
for i in stride(from: 0, to: 100, by: 1) { print(i) // prints from 0 to 99 and by is increement value i.e. 1 } |
Using stride(from:through:by:) it will include the value of last value that you will give through: field and set by: field value that is incremented value example:-
1 2 3 |
for i in stride(from: 0, through: 100, by: 1) { print(i) // prints from 0 to 99 and by is increement value i.e. 1 } |