Junior — Middle
What type of data does a closure represent in programming?
sobes.tech AI
Answer from AI
In programming, a closure is a data type that represents a block of code along with variables captured from the surrounding context. A closure can be stored in a variable, passed as a parameter, or returned from a function.
Simply put, a closure is a function with a "capture" of external variables that remain accessible even after leaving the scope where they were declared.
Example in Swift:
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
let incrementer: () -> Int = {
total += amount
return total
}
return incrementer
}
let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen()) // 10
print(incrementByTen()) // 20
Here, the closure captures the variable total and modifies it each time it is called.