Adam S Adam S - 8 days ago 8
Swift Question

How can I do a Swift for-in loop with a step?

With the removal of the traditional C-style for-loop in Swift 3.0, how can I do the following?

for (i = 1; i < max; i+=2) {
// Do something
}


In Python, the for-in control flow statement has an optional step value:

for i in range(1, max, 2):
# Do something


But the Swift range operator appears to have no equivalent:

for i in 1..<max {
// Do something
}

Answer

The Swift synonym for a "step" is "stride" - the Strideable protocol in fact, implemented by many common numerical types.

The equivalent of (i = 1; i < max; i+=2) is:

for i in 1.stride(to: max, by: 2) {
    // Do something
}

Alternatively, to get the equivalent of i<=max, use the through variant:

for i in 1.stride(through: max, by: 2) {
    // Do something
}

Note that stride returns a StrideTo/StrideThrough, which conforms to SequenceType, so anything anything you can do with a sequence, you can do with the result of a call to stride (ie map, forEach, filter, etc). For example:

1.stride(to: max, by: 2).forEach { i in
    // Do something
}