Define Swift Closures
Written by Team Kodeco
In Swift, closures are self-contained blocks of code that can be passed around and used in your program. They are similar to functions, but have a more flexible syntax and can be stored as variables or used as function arguments.
Here is the basic syntax to define a Swift closure:
{ (parameters) -> returnType in
statements
}
Here’s a concrete example of that:
let addTwoNumbers = { (a: Int, b: Int) -> Int in
return a + b
}
let sum = addTwoNumbers(3, 5)
print(sum) // Output: 8
Specify the Type of a Closure
To specify the type of a closure, use this syntax:
(parameterTypes) -> returnType
Where parameterTypes
is a list of the data types of the closure’s input parameters and returnType
is the data type of the value returned by the closure.
For example, the type of the addTwoNumbers
closure from earlier would be (Int, Int) -> String
.
So you could have written that example as follows:
let addTwoNumbers: (Int, Int) -> Int
addTwoNumbers = { (a: Int, b: Int) -> Int in
return a + b
}
Shorthand Syntax with Swift Type Inference
If the compiler can infer the types of the parameters and the type of the return type, you can use a shorthand syntax for closures as follows:
{ (parameters) in
statements
}
For example, thanks to Swift type inference you can shorten the previous example as follows:
let addTwoNumbers: (Int, Int) -> Int
addTwoNumbers = { a, b in
return a + b
}
This works because the compiler knows addTwoNumbers
is a closure that takes two Int
s and returns an Int
from the type annotation, so you don’t need to re-specify that when you declare the closure.
Closures with no Parameters
If a closure takes no parameters and returns nothing, you can use an extremely abbreviated syntax:
let printHello = { print("Hi there!") }
The type of printHello
is () -> Void
, or in shorthand syntax, () -> ()
.
Closures are very powerful in swift, they are used in many functional programming techniques like map
, filter
, reduce
and other higher-order functions.