Thursday, 11 May 2017

Closure Capture list

In Swift, closures are reference type means they reference to objects and properties which comes in the defined context of the closure. What it's means? To understand this concept, let's have a look on  this example:

var a = 23
var b = 35


Note: I am not digging in the deep about what is closure and how it work. I assume you already know the basics of the closure. By definition closure is an object like other objects in Swift which can be stored, referenced and passed as a argument to the functions .

Now create a closure which will print the value of these two variable.

var myClosure: () -> ()  = { print("a = \(a) and b = \(b)") }


Here we define  a closure and stored it in a myClosoure . We can call a closure like any other function s in Swift as:

myClosure()

This will print the value of a and b   as:

a = 23 and b = 35

Now try to change the value of  a and b and then call the  closure 

a = 45
b = 55
myClosure()

The output will be 

a = 45 and b = 55

What is this? It means closure captures the latest value  of the properties and object which comes in the defined context of the  closure. 

Now we have idea of how closure is reference type.  A closure in Swift keeps the reference to the properties , it doesn't copy them by default. But we can changes this default behavior  of the closure means in Swift it's possible to allow closure to copy the value of properties and objects in the defined context of the object. The rescue is called Capture List .

To allow a closure to copy the properties of the object we pass these value in an array which is called Capture List. 

To copy the value we add these value in an array and place this array before in keyword in a closure.

Now edit the above defined closure in order to copy the value of the properties like this:

var a = 23
var b = 35

let  myCopyClosure:() -> () = { [a ,b] in 
              print("a = \(a) and b = \(b)") 
               }

//call the closure
myCopyClosure()

This will print the value as earlier:

a = 23 and b = 35

Try to change the value and then call the closure 

a = 45
b = 55
myCopyClosure()

Now the output will be

a = 23 and b = 35


Did you see the difference?  This time closure copy the value of properties which are added in the capture list of the closure. The closure copy the value of  a property , it's have at the time when we defined the closure. Now it's doesn't matter how many time we change the value of a  and b .

Reference: Official document of Swift from Apple

No comments:

Post a Comment