Vladislav Brylinskiy
Vladislav Brylinskiy

Reputation: 559

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"

Upvotes: 0

Views: 545

Answers (1)

matt
matt

Reputation: 535231

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.

Upvotes: 3

Related Questions