Vladislav Brylinskiy Vladislav Brylinskiy - 6 months ago 10
Swift Question

Scope of index in for-in loop - swift

Do I correctly understand that there is no way to pass a local variable as an index in for-in loop so that this variable will be modified after loop ends?

var i = 0
for i in 0..<10 {
}
print(i)

// prints "0" but I expected "10"

Answer

Correct. The way you've written it, the i in for i overshadows the var i inside the for loop scope. This is deliberate. There are many other ways to do what you want to do, though. For example, you might write something more like this:

var i = 0
for _ in 0..<10 {
    i += 1
    // ...
}

Or use a different name:

var i = 0
for ii in 0..<10 {
    i = ii
    // ...
}

Personally, I'd be more inclined here to use a while loop:

var i = 0
while i < 10 {
    i += 1
    // ...
}

A for loop can always be unrolled into a while loop, so there's no loss of generality here.