var array = [() -> ()]()
var count = 0
var index = 0
while index < 5 {
array.append {
print("count: \(count)")
print("index: \(index)")
}
count += 1
index += 1
}
array[0]()
array[4]()
Output:
count: 5
index: 5
count: 5
index: 5
Same case but with some changes:
var array = [() -> ()]()
var count = 0
for index in 0..<5 {
array.append {
print("count: \(count)")
print("index: \(index)")
}
count += 1
}
array[0]()
array[4]()
Output:
count: 5
index: 0
count: 5
index: 4
Count
value would be the same in both the cases as we are not explicitly capturing it, i.e 5
- In the first case global
index
variable is used and the result is the last incremented value i.e. 5 and 5 - In the second case for loop's
index
is used and the value is 0 and 4 respectively.
What is the exact difference?
In the first example
index
isvar
declared and it is the same variable used each time, in the second it islet
declared so in the second example it is a new instance ofindex
that exists in the scope of thefor
loop for each iteration