Blog / April 25, 2023 / 3 mins read / By Mahi Garg

Closures: Swift

Closures are a powerful feature of the Swift programming language that allows you to write code that can be passed around and executed at a later time. They are self-contained blocks of functionality.

Closures are commonly used in Swift to perform tasks like sorting and filtering collections and for handling asynchronous tasks.

Syntax:

A closure is defined using curly braces { } and can take in one or more arguments, and returns a value. Here’s a basic syntax of a closure:

{ (params) -> return type in
  // Statement
}
  • params — any value passed to the closure
  • returnType — specifies the type of value returned by the closure
  • in (optional) — used to separate parameters/returnType from the closure body
  • Statement — code to be executed.

Closures need not have the first 3 always. Find the below examples supporting the statement.

var sayHi = {
  print("Hey!")
}

// call the closure
sayHi()                        // output is Hey!

This example of closure prints a string. It doesn’t require any parameters. It doesn’t return anything. It just has a single line of code to execute.

Now let us see other examples of closure where we have either a parameter or a return type.

let sayHi = { (name: String) in
  print("Hey!, \(name).")

}

// closure call
sayHi("Mahi")                 // output is Hey!, Mahi

let taskCompleted = { ()-> String in
  return "Bravo You Are Done!" 
}

// closure call
print(taskCompleted())         // output is Bravo You Are Done!

Hope you have understood what is closure. How to write closure in Swift. Now let us move to the usage of closure in Swift.

Now let us consider a block of code that needs to be executed after the method has completed its task. Let us have a look below for example.

func add(first: Int, second: Int, completion: (Int) -> String) {

  let sum = first + second
  print(completion(sum))

}

add(first: 4, second: 56) { result in
  return "result is \(result)"
}                       // output is result is 60

add(first: 4, second: 56) { result in
  return "sum is \(result)"
}                       // output is sum is 60

Here method add takes 2 integers and 1 closure as arguments. It performs the sum of 2 numbers. After the addition is done it calls the closure to print the result according to the code written in the closure.

Here, the first method call defines the closure to return the string “result is 60” while the second return the string “sum is 60”. So we can conclude that closure also gives the power to the method to execute a different set of code depending on where it is called.

Comments