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

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

原文链接:https://www.f2er.com/swift/318649.html

猜你在找的Swift相关文章