gpt4 book ai didi

swift - 在闭环中捕捉值(value)

转载 作者:行者123 更新时间:2023-11-28 12:51:37 25 4
gpt4 key购买 nike

Apple Swift 编程指南 (2.2) 指出

A closure can capture constants and variables from the surrounding context in which it is defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.

例子:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen()
// returns a value of 10
incrementByTen()
// returns a value of 20
incrementByTen()
// returns a value of 30

问题出现了,这个值是如何保存而不是重置的?我来自 C 背景,这在我看来就像 3 个函数调用和 3 个不同的堆栈框架。但似乎该值未被覆盖。这是否意味着如果闭包使用其周围的上下文变量,它不会被编译器删除并且如果使用不当可能会导致内存泄漏?

最佳答案

Does it mean that if a closure uses its surrounding context variable it does not get erased by the compiler and can cause memory leaks if not used correctly?

当然可以,但在本例中并非如此。让我分解一下。从 makeIncrementer 函数开始:

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

func incrementer 引用 runningTotal,它在其自身范围之外。因此 runningTotalfunc incrementer 捕获

现在考虑周围的函数 makeIncrementer 做了什么:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
// ...
func incrementer() -> Int {
// ...
}
return incrementer
}

它声明func incrementer 并返回它。那么现在考虑当我们调用那个周围的函数时会发生什么:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
// ...
return incrementer
}
let incrementByTen = makeIncrementer(forIncrement: 10)

最后一行调用 makeIncrementer,我们刚才说它返回了一个函数。它还该函数分配给一个变量incrementByTen。这是一个本地(自动)变量。所以是的,这个函数会被保留,但只要 incrementByTen 存在,就不会太久,因为它只是作为一个自动局部变量在堆栈上。

但只要 incrementByTen 确实 存在,它就会保留该函数,并且我们在开始时说过,该函数已捕获 runningTotal并将其维护在一种 float 的本地空间中。因此,incrementByTen 指向的函数可以被多次调用,而 float 的runningTotal 保持存活并不断递增。

关于swift - 在闭环中捕捉值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378768/

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