Swift: The stride() Function

stride() Function in Swift:

The forin loop gives you the flexibility to choose how to iterate through the sequence using the stride() function in Swift.

stride(from: x, to: y, by: z)

Note that we need to provide 3 comma separated values to use stride() function in a forin loop:

for count in stride(from: 2, to: 8, by: 2) {
  print(count);
}

The output will be:

2
4
6

Arguments are the values we provide to functions. There is an argument label in each argument, such as from:, to:, or by:. We’ll go over functions in greater detail in a later lesson, but here’s a sneak peek:

  • The first argument, from: 2, is the sequence’s starting number (2).
  • The second argument, to: 8, is the sequence’s end (8). However, you’ll notice that we didn’t print out 8, indicating that this final number isn’t included.
  • The third argument, by: 2, specifies how much to increment (or decrement, if a negative number is used) during each iteration. In the loop, the value of count changes as follows:
iteration #count Value
First2
Second4
Third6

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: