swift

I had a bit of trouble digesting the closure, probably I'm still be in the digestion phase. The first example in the Swift manual is quite effective and I follow it but giving to it a different path.

The manual defines the closure exactly (obviously) but once you read the definition you do not have the feeling that you understand.

Thinking for a long time as I would explain closure to a friend I obtained that the most effective way would be to say that closure are a way to shrink up in a small space functions that if written in usual way they would spend several lines of code. The resulting summary however maintains a level of readability that makes it possible to understand the meaning of the function. Here is the example of the manual with the function before and after the treatment.

 

//An array of strings to sort

let names = ["Paolo", "Carlo", "Antonella", "Elisabetta", "Marco"]

 

// Method without closure. Sorted function belongs to the array type.

func inverseOrder(_ s1: String, s2: String) -> Bool {

    return s1 > s2

}

var reversedNames = names.sorted(by: inverseOrder)

 

// Same as above but with closure (the inverseOrder function is no more needed)

var reversedNames2 = names.sorted(by: >)

 

The example rotates around the sorted function that is a method of the array. This function takes as a parameter another function that is meant to indicate how you want the array to be sorted.

In the first example we pass the inverseOrder function as parameter to the sorted function. The inverseOrder function is of type (String, String) -> Bool it compares two strings and returns true if the first is higher than the second. This answer is provided by comparing with the operator '>'.

The closure does not do anything else (so to speak) that save us the burden of writing types, return values, headings of the function, to take the only element that really counts within the function: the operator '>'. 

It is the compiler who can infer what we mean by putting the '>' symbol only, meaning that the definition of the function is superfluous. This is the Swift language message: simplification.

A first general rule: closure applies to functions; it is particularly useful for simplifying nested functions.

The code below I think it is self explanatory.

 

// Freely inspired by video tutorial of Ray Wenderlich (www.raywenderlich.com)

// First we define the closure type

var multiplyClosure: (Int, Int) -> Int

 

// Then we implement the body of the closure in this way

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

    return a * b

}

// and also in this way, that is the same as above

multiplyClosure = { $0 * $1 }

 

// Now we use the closure

let result = multiplyClosure(4, 3)

 

// We define a new closure that sum instead of multiply

var sumClosure: ( Int, Int ) -> Int = { $0 + $1 }

 

// We define a function that takes a function as parameter

func operationOnNumbers (_ a: Int, _ b: Int, _ operation: (Int, Int) -> Int) -> Int {

    return operation(a, b)

}

 

// We use the function just defined passing the closure as parameter

operationOnNumbers(3, 6, multiplyClosure)   //18

operationOnNumbers(3, 6, sumClosure)        //9

 

// Same as above but writing the closure directly here

operationOnNumbers(12, 6, { $0 / $1 })      //2

 

 

Two words of explanation. Where we define the first closure we use the statement in. Everithing appears after in is the body of the closure: where we define the operations on the defined parameters.

The shrinked multiplyClosure is defined just using $0 and $1 as parameter. This is obtained by removing the type Int, the parentesis, the return statement and even the name of the parameters. Swift doesn't need what it can infer. $0 and $1 are the default names of the variables that we don't want to define.