gpt4 book ai didi

swift - 闭包如何存储对常量或值的引用

转载 作者:可可西里 更新时间:2023-11-01 00:59:14 25 4
gpt4 key购买 nike

描述来自swift office document

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables.

我不完全理解商店引用部分。这是否意味着它创建了某种指向变量的“指针”?如果值发生变化,“取消引用的指针”也会更改为新值。我认为 Swift 没有指针概念。我借用它来表达我的理解。

如果有人可以提供简单的代码行来解释闭包如何存储对常量/变量的引用,那就太好了。

最佳答案

Does it means It creates some sort of "Pointer" to a variable? If the value changed the "de-referenced pointer" also changed to the new value.

是的。

I think Swift has no pointer concept.

它肯定会以引用类型(类)的(隐式)形式和 UnsafePointer 的(显式)形式

这是一个在闭包中捕获变量的示例。这一切恰好是单线程的,但你可以让这个闭包由中央调度调度。 x 被捕获,因此它在闭包的整个生命周期中都存在,即使闭包存在于 x 的声明范围(f())之后>) 退出。

func f() {
var x = 0 //captured variable

_ = {
x = 5 //captures x from parent scope, and modifies it
}()

print(x) //prints 5, as x was modified by the closure
}

f()

我写了another answer这解释了函数、闭包和其他术语之间的关系。 IMO,值得一读。

关于swift - 闭包如何存储对常量或值的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951484/

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