0

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"
1

1 Answer 1

3

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.

3
  • 3
    There is no ++ in modern Swift, @CharlieMartin.
    – matt
    May 17, 2016 at 19:44
  • 1
    Starting from swift 3 there won't be ++, @ CharlieMartin. May 17, 2016 at 19:44
  • Thanks. I figured that must be it May 17, 2016 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.