How can I do a Swift for-in loop with a step?
Solution 1:
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 stride(from: 1, to: max, by: 2) {
// Do something
}
Alternatively, to get the equivalent of i<=max
, use the through
variant:
for i in stride(from: 1, through: max, by: 2) {
// Do something
}
Note that stride
returns a StrideTo
/StrideThrough
, which conforms to Sequence
, so 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:
stride(from: 1, to: max, by: 2).forEach { i in
// Do something
}