简体   繁体   English

如果未在Swift的内部范围中使用闭包变量,是否不保留?

[英]Does a closure variable not retained if not used in inner scope in Swift?

I have a function like below: 我有如下功能:

func fetchComment(postId: String, index: Int, callback: @escaping (_ comment: Comment) -> Void) {
    rtDB!.fetchComment(postId: postId, callback: { comment in
        self.log.debug("postId: \(postId) - comment: \(comment)")
        self.fetchUsersForComments([postId: comment], callback: { usersList in
            // self.log.debug("++++  postId: \(postId) - comment: \(comment)")    // 1
            self.log.debug("postId: \(postId) - usersList: \(usersList)")
        })
    })
}

If I add a breakpoint at 1 with that line commented out, and print p comment , I get undefined identifier comment message. 如果我在1处添加断点并注释掉了该行,并打印p comment ,则会得到未定义的标识符comment消息。 But comment is passed as the closure argument to fetchComment method. 但是comment是作为fetchComment方法的闭包参数传​​递的。 However if I uncomment the line marked 1 which uses the comment variable, and then print p comment with a breakpoint, it works fine. 但是,如果我取消注释使用comment变量的标记为1的行,然后打印带有断点的p comment ,则效果很好。 Why does the comment variable not defined if it is not being used in inner scope? 如果未在内部作用域中使用comment变量,为什么未定义? Is it Swift compiler doing optimisation and removing the variable? Swift编译器是否正在执行优化并删除变量? I have no optimisation enabled for debug more. 我没有启用优化以进行更多调试。

The reason why you can't print comment when the line is uncommented is because you are currently in the scope of the closure, and closures by default don't capture anything. 取消注释行时无法打印comment的原因是,您当前处于闭包的范围内,默认情况下闭包不捕获任何内容。 It's as if you are in another separate method. 就像您在另一种单独的方法中一样。

When you uncomment the line, you are now using the comment variable inside the closure. 当您取消注释该行时,您现在正在使用闭包内部的comment变量。 This means that the closure has to capture it. 这意味着闭包必须捕获它。 In the context of the "separate method" analogy, this is like the separate method takes an extra parameter called comment . 在“单独方法”类比的上下文中,这就像单独方法需要一个称为comment的额外参数一样。

Read more here 在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM