Revisiting Reverse Ranges in Swift

In a previous post, I wrote about working with reverse ranges in Swift. One day after that post was published, Apple released Xcode 6 Beta 4.

Xcode beta 4 added two functions to iterate on ranges with a step other than one: stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges.

To iterate on a range in reverse order, they can be used as below:

for index in stride(from: 5, to: 1, by: -1) {
    println(index)
}
//prints 5, 4, 3, 2

for index in stride(from: 5, through: 1, by: -1) {
    println(index)
}
//prints 5, 4, 3, 2, 1

Note that neither of those is a Range member function. They are global functions that return either a StrideTo or a StrideThrough struct, which are defined differently from the Range struct.

There's still not much to say on this, and the Beta 4 release notes suggest there are still changes on the way to accommodate negative ranges. At least, the weird cases that came up with by() are gone.