What is Closure in Swift?
In Swift, a closure is a self-contained block of code that can be assigned to a variable, passed as a parameter to a function, or returned from a function. Closures are similar to functions, but they are often used for more concise and portable code.
Closures capture and store references to the variables and constants from the surrounding context in which they are defined. This allows closures to carry along the context in which they were created. There are three main types of closures in Swift:
Global Functions: These are regular named functions defined at the global scope.
Nested Functions: These are functions defined within the body of another function. Nested functions can capture variables from their containing function and use them within their own body.
Closure Expressions (or simply, Closures): These are unnamed, self-contained blocks of code that can capture and store references to variables and constants from the surrounding context. Closure expressions are often used as arguments to functions, stored in variables, or returned from functions.
Here example about sum two numbers:
let addClosure: (Int, Int) -> Int = { (a, b) in
return a + b
}
let result = addClosure(5, 3) // result will be 8
Closures in Swift are powerful constructs that provide a flexible way to encapsulate functionality and manage code blocks in a concise manner.