【问题标题】:`self` in Swift closureSwift 闭包中的“self”
【发布时间】:2018-10-11 16:02:56
【问题描述】:

我想在 Swift 闭包中理解 self。 对于前 -

() -> Void = { [weak self] in
    guard let `self` = self else { 
        self.callMethod2()
    }
    self.callMethod3()
}

为什么我们在这里使用反引号? 这是良好的编程习惯吗? 这里的self怎么被弱捕获了?

【问题讨论】:

标签: swift closures


【解决方案1】:

self 是 Swift 中的保留字。由于您正在创建一个名为 self 的新本地变量,因此您需要用反引号标记它,如 rmaddy 的链接中所述。

请注意,将弱 self 映射到强 var 的通常约定是使用名称 strongSelf

() -> Void = { [weak self] in
    guard let strongSelf = self else { 
        //your code to call self.callMethod2() can't succeed inside the guard (since in that case weak self is nil)
        //self.callMethod2()
        return   //You must have a statement like return, break, fatalEror, or continue that breaks the flow of control if the guard statement fails
    }
    strongSelf.callMethod3()
}

【讨论】:

  • @Hamish 感谢您清理我的代码格式。有点忘了代码块缩进...
【解决方案2】:

Swift 4.2 最近通过了一项将其添加到语言中的提议:

guard let self = self else { return }

建议的解决方案需要允许使用可选绑定将 self 从弱引用升级到强引用。

更多详情请参考快速进化提案SE-0079

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2016-05-02
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多