Thursday, July 5, 2018

Swift Closures Capture List


In this tutorial Let’s see how closure takes the variables in the context.


       
 var fruit = "Apple"

  let closure = {
      return fruit
  }

  print("\(closure())")  //Apple

  fruit = "Banana"

  print("\(closure())")  //Banana



In this case, closure takes fruit as reference. I mean, If we change the value of fruit and call closure again, We see the new value.

Closures by default take reference and use the values.

Now, What If we don’t need any new values for closure?

We can add capture list like shown below.


       
 var fruit = "Apple"

  let closure = { [fruit] in
      return fruit
  }

  print("\(closure())")  //Apple

  fruit = "Banana"

  print("\(closure())")  //Apple



[fruit] in is nothing but a capture list which creates immutable copies.

Here fruit will be passed as an immutable copy to the closure. Means, though we change the value of fruit, As closure captured immutable copy of fruit, The new value will not get reflected.

As it is an immutable copy, If we try to change the value inside closure, We will get compiler warning.


       
 var fruit = "Apple"

  let closure = { [fruit] in
      fruit = "Mango"   //Compiler warning!
      print("\(fruit)")
  }

  closure()  //Apple

  fruit = "Banana"

  closure()  //Apple


  Playground execution failed:

  error: closure.playground:16:11: error: cannot assign to value: 'fruit' is an immutable capture
    fruit = "mango"
    ~~~~~ ^



Hope this post is useful. Feel free to comment incase of any queries.



1 comment:

  1. I would like to thank you for the efforts you have made in writing this article, Its good and Informative.
    ios online training

    ReplyDelete