14. Closures in Swift

Function without name is called Closure. A self-contained block of code which can closed over constants and variables is called closure. Following code is a simplest form of closure.

let cl_HelloWorld = { println("Hello Closure") }

Closures, same like functions, can accept values and can return some result as well. The only difference is that you can assign this block of code to a variable and you can call this closure via the variable as a reference. Lets discuss the syntax of a closures

A simple Closure without parameters and return type

A closure which does not take any parameter and does not return any value looks like this.

A Code block { }, no parameter with empty brackets (), no return type with empty brackets() and ‘in’ side the closure, your code .

var cl0_squarenumber = { () ->  () in

    println("hello")
}

 

Closure with parameters and return type

Exactly like functions, closure can accept parameters and can return value as well. Add parameter list is first set of brackets (param1, param,2… ) and declare the return type after arrow sign.

var cl1_squarenumber = {(a: Int) -> Int in

    return a * a

}

cl1_squarenumber(5)

You can call this closure by variable cl1_squarenumber which has reference to closure. One important this is, parameters are constants by default so you can not change the value as long as you declare it as variable.

var cl2_addnumber = {(var a: Int) -> Int in

    var b = 5
    a = a + b

    return a

}

Swift is quite flexible and it facilitates developers while writing code. Check this example, following closure takes two parameters and returns integer value.

var cl3_multiplynumber = {(a: Int,b: Int) -> Int in

    return a * b
}

cl3_multiplynumber(6,7)

Now see the difference:

var cl3_multiplynumber = {(a,b) -> Int in  

    a * b

}
cl3_multiplynumber(6,7)

There is no parameter type defined and there is no return keyword in last line but it still works exactly the same. Actually Swift is very intelligent, it can check the variable type when you pass it and by default the last line of the code is returned value.

Swift also allows to declare the closure signatures first:

var cl5_addTwoNumbers:(Int,Int)->Int

and then you can use it in very flexible way.

cl5_addTwoNumbers = { $0 + $1 }

You should not be worried about the name of parameters. You can call first parameter with $0 and second with $1. You can see that its very clean way to add two numbers and return the result.

cl5_addTwoNumbers(5,7)

 

Closures and functions

You can pass the closures as a parameter to function. Create a closure which takes to parameters, compares them and returns boolean value.

var cl1_sortNumbers = { (a: Int, b : Int ) -> Bool in

    return a > b
}

As you can see this closure takes 2 integers type variables. It returns true if ‘a’ is greater than ‘b’ false otherwise. Create an array called number and assign some values.

var numbers = [8,3,5,1,7,6]

Swift provides some built-in functions which you can use with array and one function or method called ‘sort’. Sort function takes closure as a parameter and sort the list.

numbers.sort(cl1_sortNumbers)

You can also pass the closure directly to function. Take a function called ‘sorted’. This function takes an array which you want to sort and closure.

let getSortedArray = sorted(numbers,{ (a: Int, b : Int ) -> Bool in

    return a > b

})

Your original array will not change but you will get the new sorted array in getSortedArray.

 

Download file from GitHub