Stride in Swift

Moving through, without a boring For loop

I’ve spent some time solving Leetcode problems. More technically I’ve had a few issues with 54. Spiral Matrix and 59. Spiral Matrix II and now I find that solutions would have been much easier had I used Stride.

Prerequisites:

  • None, a basic knowledge of programming in Swift would be helpful

Terminology

Sequentially: A logical order or sequence

Stride: A function to stride over values of any type

The problem

Imagine you want to move through an array.

The traditional way is to use a for loop. An alternative is to use stride, and that produces the same result.

The syntax is rather different, but at first glance you can pick one or the other and be relatively pleased with either choice.

This article is about choosing Stride in Swift. Why?

The advantages of Stride over a for loop

  • You can move through an array or set of numbers sequentially, in units that may be larger than one
  • Negative values are possible!
  • Stride works with non-Integer values

Let us look at these step-by-step:

Moving in units larger than one (although, of course one is also acceptable)

this can be by: 1 of course.

Negative values in Stride

This works kind of “in reverse” from the normal stride. Start high, and move negatively.

Stride with non-Integer values

We can use Stride with non-Integer values.

Wait! There are two Strides?

We can actually see from the compiler’s autocomplete that there are two Strides; StrideThrough and StrideTo,

Image for post
Image for post

It might not be a surprise, but one of these goes to the last value and one includes it. Which one? take a look at the code below:

Want to take a look at a video

Ok, no problem.

The Leetcode problem

Leetcode 34 ramps things up a little bit further.

It asks us to output a spiral from a 2-dimensional matrix.

Image for post
Image for post
The output of this matrix is 1, 2, 3, 6, 9, 8, 7, 4, and 5 when written out as a spiral

You probably know the solution from here. A judicious use of Stride will help us out. Here is a solution:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store