Articles, podcasts and news about Swift development, by John Sundell.

Overriding self with a weak reference

Published on 12 Jun 2017

Avoid memory leaks when accidentially refering to self in closures by overriding it locally with a weak reference:

dataLoader.loadData(from: url) { [weak self] result in
    guard let self = self else { 
        return 
    }

    self.cache(result)
    
    ...

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.