微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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评论.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐