Closures in Swift

Promise Ochornma
2 min readMay 15, 2021
Photo by Markus Spiske on Unsplash

According to the swift official documentation

Closures are self-contained blocks of functionality that can be passed around and used in your code.

They are similar to lambda in other languages and can be used in higher order functions.

In swift, you can represent a function as a variable using closure.

Using the code snippets below, we are going to go from writing a function to writing a closure and at such learn how to convert a function into a closure.

The code above is a function that concatenates first name and last name into a full name.

We will now convert it to a closure as shown below.

In the above code snippet, we have converted the function fullName to a variable named fullName using closure.

Both codes prints out same result

“The Full Name is Promise Ochornma”

We can also simplify the closures by using the dollar sign as seen in the code snippet below.

Note that the first parameter is represented with $0, the second parameter $1. That means if we have n number of parameters, you can access at position p each using $p-1 and the full parameters will be in the range of $0…$n-1

Arrays of closure

Since a closure is a function represented as a variable, you can create an array of closures.

According to swift documentation:

An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

This means that all closures in the array must be of same type and a particular closure can be in different positions.

Just like your usual array, you can Iterating over the array using for-in loop, add two arrays using the + symbol and also add a new item using the append method

Let us now create an array of closures and see how to use them.

Dictionary of Closures

According to swift documentation:

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary don’t have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.

--

--