Khanh Nguyen Khanh Nguyen - 7 months ago 23
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 { ... }


and

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


The later one will fail at run-time. I can wrap the loop with an
if
, 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

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

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