0
0
Swiftprogramming~5 mins

Stride for custom step in Swift

Choose your learning style9 modes available
Introduction

Stride lets you count numbers with a custom step size easily. It helps when you want to skip numbers or count in jumps.

When you want to count every 2 or 3 numbers instead of every single number.
When you need to loop through a range but only want certain steps, like every 5 minutes in a clock.
When you want to create a sequence of numbers that increase or decrease by a fixed amount.
When you want to avoid writing manual math to jump steps in a loop.
Syntax
Swift
stride(from: start, to: end, by: step)
stride(from: start, through: end, by: step)

from is where counting starts.

to stops before this number, through includes this number.

Examples
Counts from 0 up to but not including 10, stepping by 2.
Swift
for number in stride(from: 0, to: 10, by: 2) {
    print(number)
}
Counts from 1 up to and including 5, stepping by 1.
Swift
for number in stride(from: 1, through: 5, by: 1) {
    print(number)
}
Counts down from 10 to just above 0, stepping down by 3.
Swift
for number in stride(from: 10, to: 0, by: -3) {
    print(number)
}
Sample Program

This program shows counting up from 0 to 15 by 3 steps, then counting down from 20 to 0 by 4 steps.

Swift
import Foundation

print("Counting up by 3:")
for number in stride(from: 0, to: 15, by: 3) {
    print(number)
}

print("Counting down by 4:")
for number in stride(from: 20, through: 0, by: -4) {
    print(number)
}
OutputSuccess
Important Notes

Use to when you want to stop before the end number.

Use through when you want to include the end number.

Negative by values let you count backwards.

Summary

Stride helps count numbers with custom steps easily.

Use to to exclude the end, through to include it.

Steps can be positive or negative for counting up or down.