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) }
    }
}