#53: Property Observers: willSet and didSet

Property observers let you run code before or after a stored property changes.

var username = "" {
    willSet {
        print("About to change to", newValue)
    }
    didSet {
        print("Changed from", oldValue, "to", username)
    }
}

Use willSet when you need the incoming value and didSet when you need the previous one.

They are handy for lightweight synchronization, logging and UI updates, but they are not a substitute for more explicit state management when things get complex.


I'm also on Twitter and GitHub.

Subscribe via RSS.