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手册,但我找不到相关说明.捕获列表用于明确设置无主,我仍然感到困惑.
什么是正确的行为,为什么会发生这种情况?

是的,记录在 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评论.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...