Reputation: 9
I do not understand how capturing values works. Below an example of a nested function that captures amount and runningTotal from its surrounding function. when calling makeIncrementer(forIncrement:) function, nothing happens inside incrementer() function (the code inside incrementer() function doesn’t get executed), so how can incrementer() capture any value? I’m obviously a novice in programming and I couldn’t find a detailed explanation of what is actually going on “under the hood”.
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incremented
}
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen()
// returns a value of 10
incrementByTen()
// returns a value of 20
incrementByTen()
// returns a value of 30
Upvotes: 1
Views: 339
Reputation: 122439
That's how closures work -- they capture variables from the surrounding scope when they are created.
Upvotes: 0