Introduction to Closures in Swift Programming
"Closures are self-contained blocks of functionality that can be passed around and used in your code." - According to Apple documentation.
Introduction
The Clousers might seem complicated at first, but it is a straightforward concept and once you understand it becomes effortless for you to use. One should already know the concept of functions in programming before understanding the closures. Closures are the very appealing concept in IOS development, and you will use it often when developing applications.👨💻 Are closures called headless functions? It is true, and I mean it let’s see why?
Let's start with example of functions
func additionFunction(number1:Int , number2:Int) -> Int {
let sum:Int = number1 + number2
return sum
}
var addition = additionFunction(number1: 12, number2: 13)
The simple addition function above take two parameters number1 and number2 and returns the sum of two variables.
Let's see the same example with closure
var addition : (Int, Int) -> Int = {(number1,number2) in
return number1 + number2
}
addition(12, 12)
we have declared a variable called addition; mentioned the data types of the variables (Int, Int) specifies that the closer with take two arguments of type Int and Int and -> Int describes that the closure will return value of type Int.
Here we have used {} brackets just like functions and (number1, number2) which are the names of the arguments.
Shorthand Closures.
There is one more way to wirte the closures without writing any argument names such as number1 and number2 using the position $0, $1. so let's see how it's done.
var addition : (Int, Int) = { in
return $0 + $1
}
In this case we are not using any argument name but we are using $0 which reffers to the first argumnent given to the closure and $1 reffers to the second argument passed to the closure. This is much shorter and clean version.
Thanks for reading this blog I hope you have learned something new and exciting today.