在使用block過程中經(jīng)常會遇到使用[weak self] 或者 [unowned self]來防止block的循環(huán)引用,通常情況下我們會使用以下語法來解決:
xx.xxBlock = {[weak self] in
guard let strongSelf = self else {return}
///code....
}
或者在代碼塊中直接使用self?或者self!解包
然而有個騷操作就是使用 而且是有效的
{[weak self] in
guard let `self` = self else {return}
self.xxx
}
Swift之父坦白,這是個bug 不過開發(fā)者似乎很喜歡這個bug
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