What's the best replacement if "Remove C-style for loops"?

I have several codes like the following:

for var i = 0; i < myarr.count; i += n { // the step is NOT 1
   // many codes
}

I knew I could use the while loop, but it seems very ugly.
var i = 0
while i < marr.count {
    // some codes

    i += n // Sometimes it is easy to be missed
}

If no C-style for loop, what's the best replacement for it ?

The below should do what you want.

for i in 0.stride(to: myarr.count, by: n) {
    // do stuff with i
}

···

On Thu, Mar 17, 2016 at 8:48 AM, nebulabox via swift-evolution < swift-evolution@swift.org> wrote:

I have several codes like the following:

for var i = 0; i < myarr.count; i += n { // the step is NOT 1
   // many codes
}

I knew I could use the while loop, but it seems very ugly.
var i = 0
while i < marr.count {
    // some codes

    i += n // Sometimes it is easy to be missed
}

If no C-style for loop, what's the best replacement for it ?

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
Trent Nadeau

The stride is what you're looking for:

for i in stride(from: 0, to: myarr.count, by: n) {
    // ...
}

In the current Swift release, you'd construct it like this though:

for i in 0.stride(to: myarr.count, by: n) {
    // ...
}

— Pyry

···

On 17 Mar 2016, at 14:48, nebulabox via swift-evolution <swift-evolution@swift.org> wrote:

I have several codes like the following:

for var i = 0; i < myarr.count; i += n { // the step is NOT 1
   // many codes
}

(…) If no C-style for loop, what's the best replacement for it ?