Skip to content
DeveloperMemos

Using Stride in Swift

Swift, Stride1 min read

Stride is a powerful function in Swift that allows you to iterate over a range of numbers with a specific increment or decrement. It's a great tool for creating sequences of numbers that don't necessarily follow the standard step of 1 in a for loop.

Basic Usage

The stride function comes in two forms: stride(from:to:by:) and stride(from:through:by:). The difference between them is whether the end value is inclusive or exclusive.

Here's an example of stride(from:to:by:):

1for i in stride(from: 0, to: 10, by: 2) {
2 print(i)
3}

This will print out the numbers 0, 2, 4, 6, and 8. Note that 10 is not included because to: is exclusive.

Now, let's look at stride(from:through:by:):

1for i in stride(from: 0, through: 10, by: 2) {
2 print(i)
3}

This will print out the numbers 0, 2, 4, 6, 8, and 10. Here, 10 is included because through: is inclusive.

Stride with Floating Point Numbers

Stride isn't limited to integers. You can also use it with floating point numbers:

1for i in stride(from: 0, to: 1.0, by: 0.1) {
2 print(i)
3}

This will print out the numbers 0.0, 0.1, 0.2, ..., 0.9. Again, 1.0 is not included because to: is exclusive.

Wrapping Up

Stride is a versatile function in Swift that provides a lot of flexibility when you need to iterate over a range of numbers with a specific step. Whether you're working with integers or floating point numbers, stride has got you covered.