努力理解为什么“通过引用捕获确保在对 makeIncrementer 的调用结束时 runningTotal 和 amount 不会消失”?

Struggling to understand why "Capturing by reference ensures that runningTotal and amount do not disappear when the call to makeIncrementer ends'?

我是 Swift 的新手,正在尝试学习捕获价值的概念。我从 "The Swift Programming Language 2.1" 看到这个:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

let incrementByTen = makeIncrement(forIncrement: 10)
incrementByTen()

“The incrementer() function doesn’t have any parameters, and yet it refers to runningTotal and amount from within its function body. It does this by capturing a reference to runningTotal and amount from the surrounding function and using them within its own function body. Capturing by reference ensures that runningTotal and amount do not disappear when the call to makeIncrementer ends, and also ensures that runningTotal is available the next time the incrementer function is called.”

如果我要问的问题对你们中的一些人来说听起来简单或愚蠢,但它一直困扰着我,请原谅我。

Q1。为什么 "capture by reference can ensure that runningTotal and amount do not disappear when the call to makeIncrementer ends"?

Q2。为什么 "capture by reference can ensure that runningTotal is available the next time the incrementer function is called"?

我发现很难在脑海中描绘和理解这些陈述。有人可以帮帮我吗?在此先感谢您的帮助!

Swift 通过ARC(自动引用计数)自动进行内存管理。在高层次上,当针对某物创建(强)引用时,计数器会增加。如果引用计数器大于 0,则对象不会从内存中释放。

因此,通过创建引用(当您从父函数捕获值时发生),您可以确保内存未被释放。

正如 Apple doc 所说:

Calling the function multiple times shows this behavior in action:
incrementByTen()
// returns a value of 10
incrementByTen()
// returns a value of 20
incrementByTen()
// returns a value of 30

Q1。为什么 "capture by reference can ensure that runningTotal and amount do not disappear when the call to makeIncrementer ends"?

A1。每次调用 incrementByTen 时,都会结束对 makeIncrementer 的调用。但是 runningTotal 的值仍然没有消失,您可以在输出中看到这一点。

Q2。为什么 "capture by reference can ensure that runningTotal is available the next time the incrementer function is called"?

A2。每次调用 incrementByTen 时,都会调用 incrementer。每次通过 incrementByTen 调用 incrementer 时,您都会得到 runningTotal 的修改值。从输出中也可以看出这一点。