Closures (Lambda) In Swift Programming

Closures are one of the most used structures in swift, it is used to create code blocks that look like functions.

In this article, we’ll learn closures and how to use these closures with function and in real projects.

What is Exactly Closure?

In Swift, closure is a special type of function that does not have a function name. It can take parameters and return values like functions.

While they are very similar to function structure, there are a few distinctions. Nested function, it’s good to know the difference between function and closure.

Before starting this article, it may be useful to learn about scopes and if you don’t know about functions, this article can help you make up for your shortcomings.

  • Function: Functions with a specific custom name, that cannot capture values (only accesses values within themselves.)
  • Nested Functions: they have a name and can capture values from their enclosing functions. (it’s not capture values outside of its main function.)
  • closures: they don’t have a special name and can capture values from the global scope.

Closures Syntax

A basic closing syntax is simple to understand, you can create a closing by writing your code in curly braces.

var name = {
  // Statement
}

caution in swift the top-level statement cannot begin with a closure expression so you have to assign the closure to a variable you can use.

You can customize the Closure a little more. For example, let’s assume that the user will enter parameters, let’s create 2 parameters.

var name = {(num1: Int, num2: Int) in
  // Statements
}

Anymore, you can use num1 and num2 parameters in your closure. We used the “in” expression for dividing parameters and closure body.

You don’t need to use the “in” statement if the closure does not contain parameters, but it is mandatory to separate the parameters from the body if contain.

It is possible to return a value with Closure, now let’s return the parameters we created earlier.

var add = {(num1: Int, num2: Int) in
   return num1 + num2
}

We have completely finished setting up a closure, next in line, we should call it in the script for use this closure.

Unlike basic functions, Closure does not use parameter labels, you must add your parameters directly.

var add = {(num1: Int, num2: Int) in
   return num1 + num2
}

var x = add(3 , 5)
print("Addition Result:" , x)
Addition Result: 8

Capturing Values With Closure

Closure can capture constants and variables from the surrounding context in which it’s defined (swift documentation).

According to this, we can use a closure with a global variable. So let’s create the first closure example.

var num1 = 22
var num2 = 7

let pi = {
  return Float(num1) / Float(num2)
}

print(pi())

As seen in the example, we were able to use 2 globally specified variables to convert to pi number in the closure.

You can also capture functions and structures but, you can’t access variables in function if your closure is not in this function.

Use Functions in Closures

Using Closures as a Function Parameter

A closure can be added as a parameter to a function, so you can use the function you created with the closure.

// Define Function
func assistant(greeting: () -> ())
{
  // Call Closure
  greeting()
}

// Call Function
assistant(greeting: {print("Hello Admin")})
Hello Admin

Let’s break down the assistant function here and examine how it works. Firstly, let’s examine the closure parameter.

The greeting is a parameter for closure value, () -> () represents the closure type and assistant is the main function for calling greeting closure.

Now, we’ll using closure with parameter as function paramater. Thanks this method, when using closures as parameters, you can add parameters to closures.

func showName(action: (String) -> Void) {
  print("Welcome,")
  action("David")
}

showName { (name: String) in 
  print("Mr. \(name)")
}

A few important points are that you must directly enter the data type you specify when assigning parameters to closures (variables are not accepted).

Leaving empty parentheses means the same as using the keyword Void, preferably using Void is easier to read.

Autoclosures

We have a keyword for using closures in a leaner way without curly braces. You can use this keyword for using closures without {}.

Auto closure is mostly used in closures that will call a single function, and it is not preferred if there is more than one line.

Automatic closures can also be used when nested functions are required. You can do the same job in a shorter way.


func display(cost: @autoclosure () -> ()) 
{
  cost()
}


display(cost: print(1209))

Leave a Reply

Your email address will not be published. Required fields are marked *