Protocol

ObservableObject

A type of object with a publisher that emits before the object has changed.

Declaration

protocol ObservableObject : AnyObject

Overview

By default an ObservableObject synthesizes an objectWillChange publisher that emits the changed value before any of its @Published properties changes.

class Contact: ObservableObject {
    @Published var name: String
    @Published var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func haveBirthday() -> Int {
        age += 1
        return age
    }
}

let john = Contact(name: "John Appleseed", age: 24)
john.objectWillChange.sink { _ in print("\(john.age) will change") }
print(john.haveBirthday())
// Prints "24 will change"
// Prints "25"

Topics

Associated Types

associatedtype ObjectWillChangePublisher

The type of publisher that emits before the object has changed.

Required.

Instance Properties

var objectWillChange: Self.ObjectWillChangePublisher

A publisher that emits before the object has changed.

Required. Default implementation provided.

Relationships

Conforming Types

See Also

Observable Objects

class ObservableObjectPublisher

A publisher that publishes changes from observable objects.