Junior — Middle
Can you tell me about the important features of using closures in programming?
sobes.tech AI
Answer from AI
Closures are functions that "remember" the context in which they were created, including access to variables from the outer scope even after that scope is no longer active.
Important features of closures:
- They allow maintaining state between function calls.
- They are used to create private variables and encapsulation.
- They are often used in asynchronous programming and event handlers.
Example in Swift:
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
return {
total += amount
return total
}
}
let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen()) // 10
print(incrementByTen()) // 20
Here, the closure retains the variable total between calls, allowing it to accumulate the value.