swift - Swift 闭包是否保留捕获的变量?

标签 swift

我发现 Swift 闭包并没有像我预期的那样保留捕获的变量。

class AAA {
}
var a1  =   AAA() as AAA?                  // expects RC == 1
var a2  =   { ()->AAA? in return a1 }      // expects RC == 2, retained by `Optional<AAA>`
a1      =   nil                            // expects RC == 1
a2()                                       // prints nil, ????

我对此感到很困惑,因为我一直认为默认情况下会保留捕获的变量。但是,如果我使用捕获列表明确捕获它,它就会被保留。

class AAA {
}
var a1  =   AAA() as AAA?
var a2  =   { [a1]()->AAA? in return a1 }
a1      =   nil
a2() // prints {AAA}, alive as expected.

我重新阅读了 Swift 手册,但找不到相关描述。捕获列表用于显式设置unowned,我仍然很困惑。 什么是正确的行为,为什么会这样?

最佳答案

是的,记录在 Capturing Values 中:

Swift determines what should be captured by reference and what should be copied by value. You don’t need to annotate amount or runningTotal to say that they can be used within the nested incrementor function. Swift also handles all memory management involved in disposing of runningTotal when it is no longer needed by the incrementor function.

规则是:如果你引用一个捕获的变量而不修改它,它是按值捕获的。相反,如果您对其进行修改,则会通过引用捕获它。当然,除非您通过定义捕获列表来显式覆盖它。

附录 以上陈述似乎是不正确的。捕获是通过引用进行的,无论它们是否在闭包内被修改。阅读@newacct 评论。

关于swift - Swift 闭包是否保留捕获的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574571/

相关文章:

swift - 定时器间隔不触发

ios - 使用 RSA 私钥签署字符串

ios - 'NSError' 不可转换为 'NSError?'

ios - 在不同的 Storyboard、Swift、iOS、Xcode 上通过 segue 和 Navigation 将数据从一个 Controller 传递到另一个 Controller

ios - 如何以编程方式在 swift ios 中自动将光标从一个文本字段移动到另一个文本字段?

ios - 如何从自定义单元格保存 UILabel 以便每次打开应用程序时它都会显示最新更改?

Swift:collectionviewHeader 委托(delegate)不起作用?

ios - 从 View Controller 访问 TableView 单元格中的 UISegmentedControl

swift - UIImagePickerController - 让用户在相机和相册之间进行选择?

ios - Swift Firebase 数据库覆盖