Table of contents
1.
Introduction
2.
Swift Closure Declaration
3.
Accepting a Parameter in Swift Closure
4.
Returning Value from a Swift Closure
5.
Passing swift Closure as a parameter
6.
Trailing Closure
7.
AutoClosure
8.
Frequently Asked Questions
8.1.
What are the types of swift Closure?
8.2.
Why closures are used in Swift?
8.3.
Why swift closures are reference types?
8.4.
What are the advantages of Swift?
8.5.
What is the capture list in Swift?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift closures

Author yuvatimankar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Swift Closure is simply a function that can be passed around. In computer science, swift closures are also known as lambda. Swift closures are like blocks in C, and lambdas in other programming languages. Swift closures can store and capture references to any constants and variables from the context in which closures are defined. All the memory management of capturing is handled by swift. 

Functions are special cases of closures and functions take three forms: Global Function, Nested Function, and closure Expression.

Source: levelupcoding

 

  • Global Functions: Global Functions have a name and it does not capture any values.
  • Nested Functions: Nested functions have a name and it captures values from the enclosing function
  • Closure Expression: Closure expressions are unnamed closures that capture values from the adjacent blocks

Swift Closure Declaration

Swift closure is declared as follows:

{ (parameters) -> returnType in
      // statements
}

 

Here,

1. Parameters is any value passed to the closure

2. returnType specifies the type of value returned by the closure

3. In is used to separate parameters/returnType from the closure body

 

Example:

var people = { 
print(“Hello, Ninja!”)
}

// Calling the closure
people()    

 

Output:

Hello, Ninja!

Accepting a Parameter in Swift Closure

Like functions, swift closure can also accept parameters. 

 

Example:

let runTo = { (place: String) in
print(“ We ran to \(place).”)
}

// Calling closure
runTo(“London”)

 

Output:

We ran to London.

Returning Value from a Swift Closure

A swift closure doesn't need to return a value; it may or may not return a value. If we want Closure to return a value, we must specify its return type and use the return statement. 

 

Example:

let weRanTo = { (place: String) -> String in
return “We ran to \(place).”
}

print(We ran to (“America”))

 

Output:

We ran to America.

Passing swift Closure as a parameter

We can create a function that can accept closure as its parameter in swift.

 

Example:

let iRanTo ={
print(“I ran to the country.”)
}

func runningTracker(newRun: () -> void) {
print(“ I ran to Mars.”)
print(“ I ran to the bottom of the ocean.”)
newRun()
}

runningTracker(newRun : iRanTo)

 

Output:

I ran to Mars.
I ran to the bottom of the ocean.
I ran to the country.

 

Here, 

  • newRun - function parameter
  • () -> () - represent the type of the closure
  • newRun() - call closure from the inside of the function.

Trailing Closure

Trailing closure is used to declare passing the function’s final argument to a closure expression. Trailing closure in swift is used after function call's parentheses. 

 

Example:

func getData ( place: String, completion:() ->() ) {
print(url)
completion()
}

getData( place:”I ran to India”) {
print(“Domino’s Pizza: 2 miles away”)
}

 

Output:

I ran to India
Domino’s Pizza: 2 miles away

 

Here, getData() function accepts a closure , completion: () -> () . Hence, function is called by passing the closure argument as function definition.

AutoClosure

@autoclosure keyword in a function definition is used to pass the closure argument without using braces.

 

Example:

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

display(greet: print(“Hello Ninja!”))

 

Output:

Hello Ninja!

Frequently Asked Questions

What are the types of swift Closure?

There are two types of swift Closure: escaping Closure and non-escaping Closure

1. An escaping closure is called after the function it was passed to returns; we can also say it outlives the function it was passed to.

2. A non-escaping closure is called within the function it was passed into before it returns.

Why closures are used in Swift?

Closures are used in swift because they can store and capture a reference to any constants and variables from the context in which they are defined.

Why swift closures are reference types?

Whenever you assign a Closure or a function to a constant or variable, you are setting that constant or variable to be a reference to the Closure or function.

What are the advantages of Swift?

The advantages of using swift are as follows:-

1. Swift programming language is easier to maintain 

2. Swift programming language is fast 

3. Swit supports dynamic libraries. 

4. Swift consists of a concise code structure.

What is the capture list in Swift?

A capture list is the list of values that you want to remain unchanged at the time the Closure is created. 

Conclusion

In this article, we have extensively discussed swift closures. We started with what swift closures are, then how to declare swift closures, and then saw some examples. 

After reading about swift closures, are you not feeling excited to read/explore more articles on the topic of Swift? Don't worry; Coding Ninjas has you covered. To learn, see the Definitive Swift Tutorial for Beginnerswhy iOS & OS X Developers are choosing Swift?, and which is better to learn? iOS or Android?

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass