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.

Sign up to request clarification or add additional context in comments.

2 Comments

There is no ++ in modern Swift, @CharlieMartin.
Starting from swift 3 there won't be ++, @ CharlieMartin.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.