#12: Capturing Variables
Question
// Swift Quiz
— objc.io (@objcio) May 8, 2019
func counter() -> (Int) -> String {
var total = 0
func add(_ x: Int) -> String {
total += x
return "\(total)"
}
return add
}
let f = counter()
f(3)
let g = counter()
g(2)
f(4)
// What's the last output?
Solution
Solution: 7
— objc.io (@objcio) May 9, 2019
Each call to counter creates a fresh total variable. add captures total, so each call to f always increments the same variable, whereas the call to g increments a different counter.
https://t.co/s7500CWmAg