Closures in Swift



Closures in Swift


Closures in simple terms is a block of code which can be called any time during the current flow of execution.


Closures have access to variables and function in the scope where they are defined.

We can consider a simple array of numbers and try to transform it into a map with closure.

let numbers = [1,2,3]

The map function considers input a closure , will start with most extensive version of it as shown below.

Iteration 1-----------------------------------------------

let newMap = numbers.map ({ (input:Int) -> Array<Int> in
    return Array(repeating:input, count: input)
})

"in" is used to separate the arguments and return type from the body.

Iteration 2-----------------------------------------------

If we see the Closure is the only parameter of the function. We can omit parentheses. We just removed () .

let newMap2 = numbers.map { (input:Int) -> Array<Int> in
    return Array(repeating:input, count: input)
}

Iteration 3-----------------------------------------------

We have implied parameter and return type , numbers is a Int Array. So "input" is implied as type Int.

Also other thing to note is single statement closure implicitly return the value of their own statement. i.e  return type of Array(repeating: input, count: input) is Array<Int> . 

So we can omit the types here as well as return keyword


let newMap3 = numbers.map { (input)  in
    Array(repeating: input, count: input)
}

Iteration 4-----------------------------------------------

The parameter names can be replaced with number for very short closures. i.e $0 as first parameter  ,  $1 as the second parameter. In our case we have only one parameter so $0 is what we would need.

let newMap4 = numbers.map {  Array(repeating: $0, count: $0) }

i.e  iteration 1 => $0 will be value "1"
      iteration 2 => $1 will be value "2"
      iteration 3 => $2 will be value "3"



Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

How to set Custom Section Header in UITableView for ios sdk version greater than 6