Closures In Swift And It’s Related Importance
1 min readMay 16, 2022
--
Closures in Swift
Closure is everywhere in Swift. If you are working with Swift you must be using closure.
What is closure?
Closures are self-contained blocks of functionality that can be passed around and used in your code
- Swift Documentation.
Let’s see an example of closure:{Code}let isEven = { (value: Int) -> Bool inreturn (value % 2 == 0) ? true : false}print("5 is \(isEven(5))"){Code}
Code Snippet — 1
Everything within the brackets { } is called as the Closure expression.
Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context
- Swift documentation
Closure expression syntax:{ (parameters) -> return type instatement}
In code snippet — 1
- The parameter name is “value” which is of type “Int”.
- The return type is “bool”.
- Statement and parameters are separated by “in” keyword.
There are various optimizations provided to the closure expression.
- Closure expression can Infer types from it context.
Swift infers the type of the parameter and type of the value it returns from the context.
Read more: https://tudip.com/blog-post/closures-in-swift-and-its-related-importance