Swift closure without ugly strongSelf

June 17, 2016

Swift closure without ugly strongSelf

Many of us come to Swift from Objective-C and for many of us word 'strongSelf' or 'weakSelf' speaks right away about one fact - we are working with block.

It is much similar in Swift with closures and we are using [weak self] or [unowned self] in order to brake strong reference cycle and avoid smelling code. However, a lot of developers, and I myself is not an exception, at first were just porting the well know pattern: you create weak reference to self and then inside the block you create a new strong reference to that weak one, so that i won't be deallocated somewhere in the process of the block's execution time. Pretty standard. Many of us are using the same technic in Swift, which looks very similar to this:

myClosure() { [weak self] in
    guard let strongSelf = self else { return }
    // ... some logic


Now, you might think that there is no other way of dealing with this. But in case you haven't been keeping up with Swift development, then this is going to be something new for you: since Swift 2.X (I don't remember which version it was specifically, but one of the 2.-ish ones) you are allowed to name your own variables with reserved keywords names, like self, for, class or whatever another keyword:

let `for` = someVariable
// .. some logic

And this is a perfectly valid code. Now, while knowing this we can rewrite our closure usage like this:

myClosure() { [weak self] in
    guard let `self` = self else { return }
    self.someProperty = newValue
    // ... some other logic

It's a subtle change but very powerful one, which is called shadowing. We are basically shadowing self keyword with the strongly referenced variable of weak self with the very same name! Isn't it awesome? Isn't it beautiful? Of course it is. You are welcome!


comments powered by Disqus