【问题标题】:Does a closure variable not retained if not used in inner scope in Swift?如果不在 Swift 的内部范围内使用,闭包变量是否不会保留?
【发布时间】:2019-02-26 07:20:15
【问题描述】:

我有如下功能:

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 方法。但是,如果我取消注释标记为1 的行,它使用comment 变量,然后用断点打印p comment,它工作正常。如果 comment 变量没有在内部范围内使用,为什么没有定义它?是 Swift 编译器进行优化并删除变量吗?我没有为调试更多启用优化。

【问题讨论】:

    标签: ios swift closures breakpoints


    【解决方案1】:

    当该行未注释时,您无法打印comment的原因是因为您当前处于闭包范围内,并且默认情况下闭包不会捕获任何内容。就好像你在另一个单独的方法中。

    当您取消注释该行时,您现在在闭包内使用comment 变量。这意味着闭包必须捕获它。在“分离方法”类比的上下文中,这就像分离方法需要一个名为comment 的额外参数。

    阅读更多here

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2016-11-13
      相关资源
      最近更新 更多