Celebrating 10 Years!

profile picture

Strong Self in Swift

September 18, 2018 - Roundwall Software

Swift 4.2 has arrived which gives us the ability to replace code bits in your weak-reference blocks like guard let strongSelf = self else { return } or guard let 'self' = self else { return } with new-fangled, more direct things like guard let self = self else { return }. This is generally nicer, easier to read and helps to prevent arguments about wether to use variables like strongSelf vs otherSelf or whatever your teammates might want.

However! I've seen quite some discussion about how this is much nicer and not much discussion about the more glaring problem. When you replace self?.doSomething() with guard let self = self else { return }, you're doing effectively the same thing. Either of these and any of the above examples will result in silent failure if the self in question has disappeared by the time your block is executing. If all you do in the else portion of your guard statements is return, I generally think this is a problem. If that else statement is triggered, isn't that usually an error? Should there be some logging? a fatalError or some such? Some alternate behavior. If all you do is return, you're making it hard on yourself later when you try to figure out why your app isn't doing what you expect.

Another minor note, if you write guard self = self else { return } all in one line as I've commonly seen, you're also making it a pain to put a breakpoint on that else statement so that you can pause your app when it does happen. This makes me sad.

So in conclusion, consider what happens in your elses, you probaly don't want to just return. Also maybe don't put it all on one line, it's ok if you take more lines, scrolling is fairly easy on modern computers.