Closure in Swift 5
Learn by examples what is Closure and how to use it in your code
Published in
2 min readMay 11, 2020
What is Closure?
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
- Closure is a function and “func” keyword
- Closure is a block of code that you can assign to a variable.
- In Swift Variables “var” and Constants “let” store information, Functions “func” execute tasks and Closures have a function code in form of a variable and can be passed around.
What are the types of the Closure?
- Closure without niether parameters nor return value.
- Closure that accepts parameters.
- Closure returns value.
- Trailing Closure
Closure without parameters or return value
var myClosure = {
print("Hello I'm a Closure")
}myClosure()
=> Hello I'm a Closure
Closure that acceptes parameters
var closure: (String) -> Void = { str in
print(str)
}var closure: (Int, Int) -> Void = { first, second in
print(first + second)
}
Since closures parameters don’t have names you can refer to them with $ + parameters number
var closure: (Int, Int) -> Void = {
print($0 + $1)
}closure(3, 2)
=> 5
Closure that returns values
var closure: () -> String = {
return "Hello Closure"
}var value = closure()print(value)
=> Hello Closure
closures can also accept parameters and return value
var addTwoNumbers: (Int, Int) -> Int = {
return $0 + $1
}
addTwoNumbers(4, 5)
=> 9
Trailing Closure
If the last parameter to a function is closure that’s called trailing closure
func callMe(closure: () -> Void) {
print("will call you")
closure()
print("did call you")
}callMe {
print("calling you...")
}=> will call you
=> calling you...
=> did call you
Another example of the trailing closure with parameter
func callMe(name: String, closure: (String) -> Void) {
print("\(name) will call you")
closure(name)
print("\(name) did call you")
}callMe(name: "Smith") { name in
print(name, "is calling you")
}=> Smith will call you
=> Smith is calling you
=> Smith did call you
Trailing closure with parameter and returns value
func callMe(name: String, closure: (String) -> String) -> String {
return closure(name)
}var whoIsCalling = callMe(name: "Smith") { (name) -> String in
return name
}print(whoIsCalling)=> Smith is calling.