The Observer Pattern

The observer pattern is used to notify an object, the observer, of state changes in another object (or list of objects). The observer maintains a list of subjects, and each subject maintains a weak reference to the observer.

In Swift, we can implement the observer pattern using a simple protocol, Observer. The observer conforms to the protocol, and any time one of its subjects is updated, the didSetSubjectProperty method is called.

protocol Observer: class {
    func didSetProperty() -> Void
}

We declare Observer as a class protocol so that the compiler will let us hold a weak reference to a property conforming to it.

class Observed {
    weak var observer: Observer?
    var name: String = "InitialName" {
        didSet {
            observer?.didSetProperty()
        }
    }
}

Usage

let observer: MyObserver = MyObserver()
let observed: Observed = Observed()

observed.observer = observer
observed.name = "Something Else"