Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for C-style loop in Swift 2.2

Tags:

ios

swift

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.
like image 554
Khanh Nguyen Avatar asked Mar 22 '16 23:03

Khanh Nguyen


People also ask

How many types of loops are there in swift programming?

There are 3 types of loops in Swift: for in loop. while loop. repeat...

How do you do a for loop in Swift?

You use the for - in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string. This example uses a for - in loop to iterate over the items in an array: let names = ["Anna", "Alex", "Brian", "Jack"] for name in names {

How do I exit a swift loop?

You can exit a loop at any time using the break keyword.


1 Answers

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

for var i in 0.stride(to: -1, by: -1) {
    print(i)
}
like image 175
Michael Avatar answered Sep 21 '22 13:09

Michael