gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:44:16 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com