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

Using property observers

Published on 13 Dec 2018
Basics article available: Properties

I really love using property observers in Swift — makes it easy to write much more reactive code, with objects that automatically react to changes in state and other values.

class ChartTableViewCell: UITableViewCell {
    var values: [CGFloat] = [] {
        // Property observers let us easily react to changes
        // in property values to, for example, re-render a
        // part of our UI:
        didSet { renderChart() }
    }
    
    // Superclass properties can also be observed, simply by
    // overriding one and adding an observation:
    override var accessoryView: UIView? {
        // 'oldValue' is automatically available within
        // didSet property observers:
        didSet { accessoryViewDidChange(from: oldValue) }
    }
}

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.