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
indexvariable is used and the result is the last incremented value i.e. 5 and 5 - In the second case for loop's
indexis used and the value is 0 and 4 respectively.
What is the exact difference?