Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)


Think of closures as a piece of code or functionality to pass around in your code. Closures in Swift are very similar to blocks in C and Objective-C. Closures in Swift are the first class type and it is allowed to be returned or passed as a parameter. And as we will see, functions are just special instances of closures. The general formula for closures is like this:

{ (params) -> returnType in

As you can see, we opened curly braces, and then we added the necessary parameters followed by the return type and the in keyword. Knowing this formula will help you a lot in using closures, and you will not feel any frustration using it.

This is an example of using closures in sorting the collection of data:

var nums = [10, 3, 20, 40, 1, 5, 11]
sorted(nums, { (number1, number2) -> Bool in
    return number1 > number2
//[40, 20, 11, 10, 5, 3, 1]

Here, the closure is used to identify the comparison result of any two numbers. As we saw, the closure takes two parameters and returns a Boolean, that is the result of the comparison.