Swift 为什么说guard let `self` = sel
2018-04-23 本文已影响56人
船长_
先看官方类似用法
demo.jpg
官方解释:
原文:https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/007425.html
Allowing `guard let self = self else { ... }` for weakly captured self in a closure.
> On Jan 5, 2016, at 8:21 PM, Christopher Rogers via swift-evolution <swift-evolution at swift.org> wrote:
>
> You can shadow self with a guard like you wrote it if use the keyword escaping backquotes like so:
>
> guard let `self` = self else { return }
To confirm what others have said down thread, this is a compiler bug: this code is valid, but shouldn’t change what references to “self.method()” or “method()" bind to (i.e., explicit or implicit references to self).
Backquotes are for forming a name that happens to overlap with a keyword. In the case of `self`, this could be because you want to refer to the NSObject.`self` method for some reason. Backquotes are not a way to name self, init, subscript or any of the other declarations that look like magic identifiers.
-Chris Lattner
Fri Jan 22 19:51:29 CST 2016
原文中明确指出这是一个编译器bug,反引号``不应该用在self
,ini
和'subscript'等这种关键字
可参考Stack Overflow 上https://stackoverflow.com/questions/24468336/how-to-correctly-handle-weak-self-in-swift-blocks-with-arguments
推荐用以下写法
guard let strongSelf = self else{ ... }
或者
if let strongSelf = self {
...
}