Types of Closures
In Swift, there are three types of closures:
1- Global functions, which are closures that have a name and do not capture any values from their surrounding context.
func greet(name: String) -> String {
return "Hello, \(name)!"
}
2-Nested functions, which are closures that are defined within the body of another function and capture values from their surrounding context.
func outerFunction() -> () -> Void {
var message = "Hello"
func innerFunction() {
message += " World"
print(message)
}
return innerFunction
}
let myFunc = outerFunction()
myFunc() // prints "Hello World"
3- Closure expressions, which are unnamed closures that can be used inline and capture values from their surrounding context.
let numbers = [1, 2, 3, 4, 5]
let doubledNumbers = numbers.map({ $0 * 2 })
print(doubledNumbers) // prints "[2, 4, 6, 8, 10]"
In the example above, the closure expression { $0 * 2 } is passed as an argument to the map method of the numbers array. This closure captures the value of $0, which represents each element of the array, and returns the doubled value of that element.
Comments
Post a Comment