Member-only story
ObservableObject vs. @Observable Macro: Streamlining SwiftUI State Management
Discover how Swift’s new macro system reduces boilerplate and transforms UI data binding with practical examples.
In SwiftUI (and related frameworks), keeping your UI in sync with your data is essential. Traditionally, you’ve done this by making your model classes conform to the ObservableObject protocol and marking properties with @Published. Recently, however, Swift has introduced an @Observable macro that can automatically synthesize much of this boilerplate for you. In this article, we’ll compare the two approaches in detail and provide examples.
Starting with iOS 17, iPadOS 17, macOS 14, tvOS 17, and watchOS 10, SwiftUI provides support for Observation, a Swift-specific implementation of the observer design pattern. Adopting Observation provides your app with the following benefits:
- Tracking optionals and collections of objects, which isn’t possible when using ObservableObject.
- Using existing data flow primitives like State and Environment instead of object-based equivalents such as StateObject and EnvironmentObject.
- Updating views based on changes to the observable properties that a view’s body reads instead of any property changes…