To understand why i can not be mutable means knowing what forβ¦in means. for i in 0..<10 extended by the compiler to the following:
var g = (0..<10).generate() while let i = g.next() {
Each time in loop i is the just declared variable, the value of the expansion of the next result when next called on the generator.
Now, that while can be written as follows:
while var i = g.next() {
but of course that would not help - g.next() is still going to generate 5 next time around the loop. The increment of the body was meaningless.
Presumably for this reason, forβ¦in does not support the same var syntax for declaring its loop counter - it would be very confusing if you did not understand how this works.
(unlike where , where you can see what happens - the var functionality is sometimes useful, just like func f(var i) can be).
If you want to skip certain iterations of the loop, your best bet (without resorting to C-style for or while ) is to use a generator that skips the corresponding values:
// iterate over every other integer for i in 0.stride(to: 10, by: 2) { print(i) } // skip a specific number for i in (0..<10).filter({ $0 != 5 }) { print(i) } let a = ["one","two","three","four"] // ok so this one's a bit convoluted... let everyOther = a.enumerate().filter { $0.0 % 2 == 0 }.map { $0.1 }.lazy for s in everyOther { print(s) }
source share