![](/img/trans.png)
[英]Assigning Closure to variable in Swift causes 'variable used before being initialized'
[英]Does a closure variable not retained if not used in inner scope in Swift?
我有如下功能:
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)")
})
})
}
如果我在1
处添加断点并注释掉了该行,并打印p comment
,则会得到未定义的标识符comment
消息。 但是comment
是作为fetchComment
方法的闭包参数传递的。 但是,如果我取消注释使用comment
变量的标记为1
的行,然后打印带有断点的p comment
,则效果很好。 如果未在内部作用域中使用comment
变量,为什么未定义? Swift编译器是否正在执行优化并删除变量? 我没有启用优化以进行更多调试。
取消注释行时无法打印comment
的原因是,您当前处于闭包的范围内,默认情况下闭包不捕获任何内容。 就像您在另一种单独的方法中一样。
当您取消注释该行时,您现在正在使用闭包内部的comment
变量。 这意味着闭包必须捕获它。 在“单独方法”类比的上下文中,这就像单独方法需要一个称为comment
的额外参数一样。
在这里阅读更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.