+44 (791) 5698 086

Stride Swift 3.0.1

Stride is an amazing and special feature in Swift (language by apple) which replaces the conventional c-style for statement loops.

Stride() is used to loop over a range of numbers. This range can be moved using any increment.

Lets look at three examples to understand three possible applications of stride in swift 3.0.1 code.

Conventional For loop

Before we begin understanding stride, lets look at the conventional c style for loop (which has been deprecated in swift 3.0.1):

for var i = 0; i < 10; i += 2 {
    print(i)
}

This worked fine, however swift engineers decided to replace it with a stride function since swift 2.2 came out (with iOS 7.0).

Using Stride() to loop over a range in Swift 3.0.1

With swift 2.2+ the conventional c style for loop is deprecated. We can use stride() instead.

With stride we can:

  • Loop over a range of numbers
  • Range can be moved using any increment
  • We can include or exclude the range maximum limit (using to or through keyword)

Look at these examples (you can try them in xcode on mac os x – tested with xcode 8.2 on macOs Sierra while writing):

Example 1:

This example simply prints the numbers 0, 2, 4, 6 and 8, excluding 10, iterating the loop 5 times.

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

Example 2:

Now the second example prints 0.0, 0.1, 0.2, 0.3 and 0.4, iterating the loop 4 times.

for i in stride(from: 0, to: 0.5, by: 0.1) { print(i) }

However, note that both these examples use the stride(from:to:by:) format. This format counts from the from to to, however excluding the last to parameter.

If we want the stride to be inclusive, rather than being exclusive, we can replace to with through, as in following example.

Example 3:

The following example prints 0, 2, 4, 6, 8 and 10. It includes the parameter provided in through too.

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

Notice how to has been replaced with through in this inclusive stride example. This example use the stride(from:through:by:) format.

I hope it clarifies the stride() and how to use it instead of conventional for loop pattern. If you’ve any questions please let me know through comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Who are we?

Nabtron team includes web, desktop software and mobile apps developers along with SEO professionals.

We are available 24 hours, 7 days a week. Contact us now for anything you need!

Join our mailing list

Lets become friend :) What's your name & email?