Closure in Swift
Closures are self-contained blocks of functionality that can be passed around as an argument and takes parameter as any object. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
Closures can capture and store references of constants and variables in the context in which they are defined. This is known as closing over those constants and variables. Thats why we call them closures.
Closure Syntax:-
Lets look at a very simple closure
This is a simple closure that doesn’t take a parameter and doesn’t return any value.
we can create a closure variable just like any other variable.
Lets look at a more useful closure which takes parameters and returns the value.
Above closure can be written with a function like
Closures can infer the type of its parameters and that of its return value
Hence the same closure above can be written as
In swift functions are closures with name. Thats why we can call our closure just like a function:-
Lets create a closure that calculates sum of two numbers
Passing Closure as argument to a function
Lets create a function that takes closure as argument:-
Trailing closure
If we pass the closure to a function as its final argument and the closure expression is long then we can take the closure out of the parentheses like above. In above example aClosure is a closure variable which takes String as parameter, prints it and returns nothing. This Closure is itself passed to the Function as parameter.
Though the closure is passed as parameter, its body is outside the parentheses ‘()’.Thats why its called as trailing closure. This makes writing a long closure as a parameter very less complicated.
Now lets take the sumClosure above with two int parameters and return value with Int type.
It takes two int parameters and returns the sum of them.
Trailing closure with parameters and return type
The function ‘addTwoNumbers’ takes the sumClosure as parameter and returns the addition.
What if we want to pass an additional parameter to the function along with the closure? we can do it as follows:-
In this Article we learned about closures and Its syntax. We also learned how we can effectively utilise them in different scenarios like Closures With param, without param, trailing closure, inferring data type of parameters from the context.