Categories
iOS Swift

Implicit self for weak self captures

Since this week has kept me extremely busy with packing our things, selling furniture, and wrapping up any loose ends before relocating back to Estonia from Japan after 4.5 years, I am going to use this week’s blog post for highlighting a new Swift 5.8 language feature. I welcome this change since how hard I try there still will be cases where I need to capture self in closures.

The language feature we are talking about is of course SE-0365: Allow implicit self for weak self captures, after self is unwrapped. Which means that if we capture self weakly in a closure, use guard let self then there is no need to write self. inside the closure any more.

Let’s take a look at a concrete example from my SignalPath app. It is a tiny change, but I feel like it makes a lot of sense. Especially because I already have explicitly handled weak self with guard let.

// Old
iqDataSource.didChangeSampleCount
.sink { [weak self] sampleCount in
guard let self else { return }
let seriesDelta = self.layout.adjust(to: sampleCount)
guard seriesDelta < 0 else { return }
self.resetTiles(priority: .immediately)
}
.store(in: &cancellables)
// New
iqDataSource.didChangeSampleCount
.sink { [weak self] sampleCount in
guard let self else { return }
let seriesDelta = layout.adjust(to: sampleCount)
guard seriesDelta < 0 else { return }
resetTiles(priority: .immediately)
}
.store(in: &cancellables)
view raw Snippet.swift hosted with ❤ by GitHub

If this was helpful, please let me know on Mastodon@toomasvahter or Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.

One reply on “Implicit self for weak self captures”