Swift closure without ugly strongSelf
June 17, 2016
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
myClosure() { [weak self] in
guard let strongSelf = self else { return }
// ... some logic
}
Swifty-way
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
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