Junior — Middle
How do closures work in terms of preserving variables from the outer scope?
sobes.tech AI
Answer from AI
Closures in Swift (and other languages) are functions or blocks of code that can capture and store references to variables from the surrounding scope where they were created. This means that even after the outer function has finished executing, the closure continues to have access to these variables and can use or modify them.
For example, if you declare a variable inside a function and return a closure that uses this variable, the variable will be retained in memory when the closure is called:
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
return {
total += amount
return total
}
}
let incrementByFive = makeIncrementer(amount: 5)
print(incrementByFive()) // 5
print(incrementByFive()) // 10
Here, total is stored inside the closure, and its value persists between calls. This is the essence of closures — preserving state from the external scope.