在使用block过程中经常会遇到使用[weak self] 或者 [unowned self]来防止block的循环引用,通常情况下我们会使用以下语法来解决:
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 不过开发者似乎很喜欢这个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
网友评论