ios - 努力理解为什么 "Capturing by reference ensures that runningTotal and amount do not disappear when the call to makeIncrementer ends' ?

标签 ios swift reference closures capture

我是 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。为什么“引用捕获可以保证runningTotal和amount在调用makeIncrementer结束时不消失”?

Q2。为什么“引用捕获可以保证下次调用incrementer函数时runningTotal可用”?

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

最佳答案

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

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

关于ios - 努力理解为什么 "Capturing by reference ensures that runningTotal and amount do not disappear when the call to makeIncrementer ends' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077642/

相关文章:

ios - 以毫秒为单位转换 DateTime iOS

ios - 仅在 Testflight 上崩溃

ios - 为选定的单元格禁用 prepareForReuse

ios - Apple TLS 与 Objective-C 和 Swift 之间的区别

ios - UITableView 中的 heightForRowAtIndexPath 有哪些替换选项?

ios - 无法将类型 '__NSDictionaryM' 的值转换为 'NSArray"

ios - 替换文本以更改音高/调

c# - 在 WCF (C#) 中引用服务时出现问题

C++ 引用和指针

C++ 成员 "Smash::smash"不是类型名称。