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

{
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,
- parameters — any value passed to closure
- returnType — specifies the type of value returned by the closure
- 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 closuresearch()
- 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!