Swift - Function Closures

Introduction

Swift closures are small, anonymous chunks of code that you can use like functions.

Closures can be passed to other functions to tell them how they should do a certain task.

The build-in sort function takes a closure, and uses that closure to determine how to compare two individual elements:

Demo

let my = [12, 5, 98, 2, 13] 
var a = my.sorted()
print(a)//from   www. j a  v  a2s  . c o  m
print(my)

Result

To sort an array so that small numbers go before large numbers:

Demo

let numbers = [12,1,56,312,120,13] 
var numbersSorted = numbers.sorted(by: { 
    (n1: Int, n2: Int) -> Bool in return n2 > n1 
}) //  ww  w .  ja  va 2 s .co  m
print(numbersSorted)

Result

The in keyword breaks up the closure from its definition and its implementation.

In the code above the definition was (n1: Int, n2: Int)->Bool, and the implementation of that closure came after the in keyword: return n2 > n1.

A closure, like a function, takes parameters.

In the preceding example, the closure specifies the name and type of the parameters that it works with.

The compiler can infer the type of the parameters for you, much like it can with variables.

You can re-write the code as follows:

Demo

let numbers = [12,1,56,32,120,13] 
let numbersSortedReverse = numbers.sorted(by: {n1, n2 in return n1 > n2}) 
print(numbersSortedReverse)

Result

If you omit the parameter names, you can refer to each parameter by number.

The first parameter is called $0, the second is called $1, etc.

If your closure only contains a single line of code, you can omit the return keyword:

Demo

let numbers = [12,1,56,32,120,13] 
var numbersSortedAgain = numbers.sorted(by: { $1 > $0 })
print(numbersSortedAgain)

Result

If a closure is the last parameter in a function call, you can put it outside the parentheses.

Demo

let numbers = [12,1,56,32,120,13] 
var numbersSortedReversedAgain = numbers.sorted { $0 > $1 } 
print(numbersSortedReversedAgain)

Result

Closures can be stored in variables. In that case, you can call them just like a function:

Demo

var comparator = {(a: Int, b:Int) in a < b} 
var a = comparator(1,2) // true 
print(a)

Result

Related Topics

Example

Exercise