Swift Closures for Laymen
What are Closures?
In technical jargon, Closures are self-contained blocks of functionality that can be passed around and used in your code.
However, speaking in laymen's terms, Closures are bodies of function without syntax — func <func_name>().
Example:
func display(message: String) {
print(message)
}
The above function can be re-written as a closure, like
{ (message) in
print(message)
}
How/When to Use Closure:
One of the most common uses of closure is callbacks. It can be used as an alternative to delegate when one-to-one communication is required. To understand its use better, consider the following scenario.
Let us start with two classes named class A and class B.
class A has:
- a stored property “name”
- a function whose only purpose is to call its argument (which is another function in this case)
class A { let name = “Nish” func callMyArgument(argument: (String) -> Void ) { argument(name) }}
class B has:
- an object of class A
- a function that prints its own argument
class B { func callMeNow(name: String) { print(name) } var a = A() a.callMyArgument(callMeNow)}
In simpler terms, this means that class B wants to call the function “callMeNow”. But B knows that this function should be called by class A because only class A knows the name argument to print.
Therefore, B cannot call the function “callMeNow(name: String)” directly because B does not have the value to its argument “name”.
But B knows that class A has a function:
func callMyArgument(argument: (String) -> Void )
that takes another function “(String) -> Void ” as its argument. So B pass its function name (without any parameter values) to class A’s function as an argument, like
a.callMyArgument(callMeNow)
Now the body of the function in A just calls its parameter with argument value, like
func callMyArgument(argument: (String) -> Void ) { argument(name)}
This “argument(name)” calls “callMeNow(name)”, and thus, printing the output as:
Nish
Cheers!