DEV Community

Cover image for Closures in Swift
Ochornma Promise
Ochornma Promise

Posted on

Closures in Swift

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.

func fullName(firstName: String, lastName: String) -> String{
  return "The Full Name is \(firstName) \(lastName)"
}

print(fullName(firstName: "Promise", lastName: "Ochornma"))

//The Result is:
//The Full Name is Promise Ochornma

Enter fullscreen mode Exit fullscreen mode

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.

let fullName: (String, String) -> String = { (firstName, lastName) in
   return "The Full Name is \(firstName) \(lastName)"
}

print(fullName("Promise", "Ochornma"))

//The Result is:
//The Full Name is Promise Ochornma

Enter fullscreen mode Exit fullscreen mode

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

let fullName: (String, String) -> String = {
   return "The Full Name is \($0) \($1)"
}

print(fullName("Promise", "Ochornma"))

//The Result is:
//The Full Name is Promise Ochornma

Enter fullscreen mode Exit fullscreen mode

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.

let plus: (Int, Int) -> Int = {
  return $0 + $1
}

let minus: (Int, Int) -> Int = {
  return $0 - $1
}

let add: (Int, Int) -> Int = {
  return $0 + $1
}

let subtract: (Int, Int) -> Int = {
  return $0 - $1
}

let closureFunctions = [ plus, minus ]

let plusSign = closureFunctions[0]
print(plusSign(1, 5))
//result is:
//6
//The append method
closureFunctions.append(add)
closureFunctions.append(subtract)

print(closureFunctions.count)
//result is:
//4
for closure in closureFunctions {
   print(closure(6,5))
}
//result is:
//11
//1
//11
//1
let addition: (Int, Int) -> Int = {
  return $0 + $1
}

let subtraction: (Int, Int) -> Int = {
  return $0 - $1
}

let closureFunctions2= [ addition, subtraction ]

let newClosureFunction = closureFunctions + closureFunctions2
print(newClosureFunction.count)
//result is:
//6
Enter fullscreen mode Exit fullscreen mode

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.

let plus: (Int, Int) -> Int = {
  return $0 + $1
}

let minus: (Int, Int) -> Int = {
  return $0 - $1
}

let add: (Int, Int) -> Int = {
  return $0 + $1
}

let subtract: (Int, Int) -> Int = {
  return $0 - $1
}

let closureFunctions = ["plus": plus, "minus" : minus ]

let plusSign = closureFunctions["plus"]
print(plusSign(1, 5))
//result is:
//6

//Add a new value to the dictionary
closureFunctions["add"] = add
closureFunctions["subtract"] = subtract

print(closureFunctions.count)
//result is:
//4

for (key, value) in closureFunctions {
  print("(\(key),\(value(5, 6)))")
}
//result is:
//(plus, 11)
//(minus, 1)
//(add, 11)
//(subtract, 1)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)