71

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
}
Adam S
  • 16,144
  • 6
  • 54
  • 81
  • 2
    Similar question: http://stackoverflow.com/questions/35032182/swift-c-style-loops-deprecated-decrement-index. – Martin R Feb 22 '16 at 15:03
  • 1
    I didn't see that one! I found [this](http://stackoverflow.com/questions/32197250/using-stride-in-swift-2-0) which led me to my answer. The keyword I was missing when I was searching (before asking the question) was "stride" - I was using the term "step" and not finding any useful results. Then when I found stride, I found Erica Sadun's [post on the topic](http://ericasadun.com/2015/05/21/swift-six-killer-features/) which is now out of date. – Adam S Feb 22 '16 at 15:06
  • I think this should be reopened. The "for loop with a step/interval" is a specific question and has the unique answer of `Stride` in Swift, which is different than the dupe Question. – pkamb Dec 03 '19 at 21:48

1 Answers1

160

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
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Adam S
  • 16,144
  • 6
  • 54
  • 81
  • 21
    in swift 3 you can use the global functions `stride(from:through:by:)` and `stride(from:to:by:)` like `for i in stride(from:1, to:max, by:2){...}` – Ricardo Pessoa Oct 19 '16 at 15:42
  • 4
    @MarkoNikolovski please don't add code to other users' answers. We don't want to put words in their mouth. Instead, add a new answer. Since this question is closed, you can add a new answer to the linked duplicate. – JAL Nov 30 '16 at 15:53