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
There are 3 types of loops in Swift: for in loop. while loop. repeat...
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 {
You can exit a loop at any time using the break keyword.
Although it's not as "pretty", you can use stride
:
for var i in 0.stride(to: -1, by: -1) {
print(i)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With