Home > Software design >  Swift: Capture list
Swift: Capture list

Time:03-26

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

  1. In the first case global index variable is used and the result is the last incremented value i.e. 5 and 5
  2. In the second case for loop's index is used and the value is 0 and 4 respectively.

What is the exact difference?

CodePudding user response:

In the first example index is var declared and it is the same variable used each time, in the second it is let declared so in the second example it is a new instance of index that exists in the scope of the for loop for each iteration

CodePudding user response:

I Debugged that code because it looked kinda weird but just let me tell you, the appending and increment line goes well, When you call array0 and array4, the debugger goes to the body of append{} and print those variables. and captures those variable from most easily accessible scope. so in first case, it will capture from the scope of function body which values are actually new 5 and 5 for both count and index.

in second case, it will try to capture if there is a variable count and index initialized, it will find count but wont find so it will check inside the body of array and there it will find the actual value which is 0 in first index and 4 in 5th index.

That's all i can explain, Sorry for bad english

Check Debugger Image Here

  • Related