Junior — Middle
Selgitage, mida tähendab muutujate haaramine sulgfunktsiooni sees.
sobes.tech AI
Vastus AI-lt
Variable capturing inside a closure function means that the closure "remembers" and can use variables from the surrounding context in which it was created.
For example, if a variable is declared inside a function and then a function that uses this variable is returned, this variable is "captured" by the closure and retains its value even after exiting the outer function.
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 captures the variables total and amount, maintaining their state between calls. This allows creating functions with internal state.