加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:39:05 所属栏目:百科 来源:网络整理
导读:我发现 Swift闭包并不像我期望的那样保留捕获的变量. class AAA {}var a1 = AAA() as AAA? // expects RC == 1var a2 = { ()-AAA? in return a1 } // expects RC == 2,retained by `OptionalAAA`a1 = nil // expects RC == 1a2() // prints nil,???? 我对此
我发现 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评论.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读