简体   繁体   English

for-in循环中的索引范围-Swift

[英]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? 我是否正确理解没有办法将局部变量作为for-in循环中的索引传递,以便在循环结束后修改此变量?

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

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

Correct. 正确。 The way you've written it, the i in for i overshadows the var i inside the for loop scope. 按照您编写它的方式, i in for i会使for循环范围内的var i黯然失色。 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: 就个人而言,我更倾向于在这里使用while循环:

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. for循环始终可以展开为while循环,因此在此不会失去一般性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM