Swift Closures

Ramesh Chavan
2 min readOct 3, 2022

--

A closure is a special type of function without the function name.

Swift Closures
{
print("Hello World")
}

Swift Closure Declaration

We don’t use the func keyword to create closure. Here's the syntax to declare a closure:

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

Here,

  1. parameters — any value passed to closure
  2. returnType — specifies the type of value returned by the closure
  3. in (optional) — used to separate parameters/returnType from closure body

Let’s see an example,

var greet = {
print("Hello, World!")
}

Closure Parameters

Similar to functions, a closure can also accept parameters. For example,

// closure that accepts one parameter
let greetUser = { (name: String) in
print("Hey there, \(name).")
}
// closure call
greetUser("Delilah")

Output

Hey there, Delilah.

Closure That Returns Value

A Swift closure may or may not return a value. If we want our closure to return some value, we need to mention it’s return type and use the return statement. For example,

// closure definition
var findSquare = { (num: Int) -> (Int) in
var square = num * num
return square
}
// closure call
var result = findSquare(3)
print("Square:",result)

Output

Square: 9

Closures as Function Parameter

In Swift, we can create a function that accepts closure as its parameter.

// define a function
func grabLunch(search: () -> ()) {

// closure call
search()
}

Here,

  • search - function parameter
  • () -> () - represents the type of the closure
  • search() - call closure from the inside of the function.

Trailing Closure

In trailing closure, if a function accepts a closure as its last parameter,

// function definition
func grabLunch(message: String, search: ()->()) {
...
}

Autoclosure

While calling a function, we can also pass the closure without using the braces {}.For example,

// using {}
display(greet:{
print("Hello World!")
}
// without using {}
display(greet: print("Hello World!"))

To pass the closure argument without using braces, we must use the @autoclosure keyword in function definition. For example,

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

Here, the @autoclosure automatically adds curly braces.

Example: Autoclosure

// define a function with automatic closure
func display(greet: @autoclosure () -> ()) {
greet()
}
// pass closure without {}
display(greet: print("Hello World!"))

Output

Hello World!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ramesh Chavan
Ramesh Chavan

Written by Ramesh Chavan

Like to work on iOS, Android, UIPath and Graph DB

No responses yet

Write a response