Articles and podcasts about Swift development, by John Sundell.

Genius Scan SDK

Presented by the Genius Scan SDK

This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.

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) }
    }
}
Genius Scan SDK

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.