0x0000600000209490 closure =100 0x0000600000209490 out 1=101 0x0000600000209490 closure =101 0x0000600000209490 out 2=101 0x0000600000209490
They all have the same address, It proves that closure capture the reference of the variable, not like block in OC.
3. Modify value in closure.
If we want to modity value in block, we should add “__block” or “__weak”, that will make the block capture reference of variable from outside. Let me see how closure handle this case.
1 2 3 4 5 6 7 8
var a =100 let closure = { a +=1 print("closure = \(a)") } print("out 1 = \(a)") closure() print("out 2 = \(a)")
Result:
1 2 3
out 1=100 closure =101 out 2=101
We can modify the value of the variable in closure directly because closure capture the reference of the variable by default.
4. Capturing list in closure.
If we capture variable in capturing list in closure, what will happen? Let me see that.
1 2 3 4 5 6 7 8 9
var a =100 let closure = { [a] in print("closure = \(a)") } a +=1 print("out 1 = \(a)") closure() print("out 2 = \(a)")
Result:
1 2 3
out 1=101 closure =100 out 2=101
At this time if we want to modify ‘a’ in closure:
1 2 3 4 5 6 7 8 9 10
var a =100 let closure = { [a] in a +=1 print("closure = \(a)") } a +=1 print("out 1 = \(a)") closure() print("out 2 = \(a)")
It will get an error like that:
And this is a tip for us that variable ‘a’ is an immutable capture now.