Use for var i in 0..<10 {
to overcome the error.
The i
in for i in 1..<10
is effectively a redeclaration of i
in the for
scope, which defaults to let
and overrides your previous declaration. No idea what your logic is doing, mind, incrementing i
in the middle of the loop. It will make no difference to the number of times the loop is executed - see below:
var i: Int = -1
print("Outer scope, i=(i)") // i=-1
for var i in 0..<10 { // Will be executed 10 times, regardless of what you do to i in the loop
print("Inner scope, i=(i)") // i=0...9, including all
if i == 2 {
i = i + 10
print("Inner, modified i=(i)") // i=12
}
}
print("Outer scope, i=(i)") // i=-1
/* Complete output:
Outer scope, i=-1
Inner scope, i=0
Inner scope, i=1
Inner scope, i=2
Inner, modified i=12
Inner scope, i=3
Inner scope, i=4
Inner scope, i=5
Inner scope, i=6
Inner scope, i=7
Inner scope, i=8
Inner scope, i=9
Outer scope, i=-1
*/
The important point is that a Swift for i in
loop is not a C for (i=0; i<10; i++)
loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…