Khanh Nguyen Khanh Nguyen - 1 year ago 68
Swift Question

Replacement for C-style loop in Swift 2.2

Swift 2.2 deprecated the C-style loop. However in some cases, the new range operator just doesn't work the same.

for var i = 0; i < -1; ++i { ... }


for i in 0..<-1 { ... }

The later one will fail at run-time. I can wrap the loop with an
, but it's a bit cluttered. Sometimes this kind of loop is useful.

Any thoughts?

Use cases

  1. You need to enumerate all elements of an array, except the last one.

  2. You need to enumerate all whole integer numbers in a decimal range, but the range can be like [0.5, 0.9] and so there's no integers (after some maths), which results in an empty loop.

Answer Source

Although it's not as "pretty", you can use stride:

for var i in 0.stride(to: -1, by: -1) {