[swift-evolution] Proposal: Allow willChange and didChange observers on a property

Nathan de Vries ndevries at apple.com
Sat Dec 5 18:00:38 CST 2015


It's currently possible to define either or both of the following observers on a property:
willSet, called just before the value is stored
didSet, called immediately after the new value is stored
I'm finding myself using didSet extensively, but almost always guard my didSet with a clause to see if the value has changed:

    class CustomView : UIView {
        var state : CustomViewState = false {
            didSet {
                guard state != oldValue else { return }
                // Act on the new state.
            }
        }
    }

Given the frequency of use, it would be great if I could strip this boilerplate altogether and simply rewrite this as:

    class CustomView : UIView {
        var state : CustomViewState = false {
            didChange {
                // Act on the new state.
            }
        }
    }

Property types conforming to Equatable would be checked for the implicit guard via ==, otherwise it would fall back on the identity operator (===) for value and reference types that don't conform to Equatable.

This would mean the following observers could be defined on a property:
willSet, called just before the value is stored
willChange, called just before the value is stored if the value is different to the previous value
didSet, called immediately after the new value is stored
didChange, called immediately after the new value is stored if the new value is different to the previous value
—Nathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151205/43eb21ce/attachment.html>


More information about the swift-evolution mailing list