Design Converter
Education
Last updated on Jan 20, 2025
Last updated on Dec 10, 2024
The introduction of @Observable in SwiftUI has revolutionized how developers handle state and data in their apps, especially with iOS 17. By leveraging the observer design pattern, SwiftUI’s new observation framework provides a powerful yet simplified approach to managing state changes across your app.
In this blog, you’ll look closer at the SwiftUI observable macro, its implementation, and how it integrates seamlessly into your SwiftUI views to improve your app's performance.
Let’s dive into @Observable's background and practical usage of @Observable, understand its benefits, and walk through examples that clarify its usage.
The @Observable macro is a new property wrapper introduced in iOS 17. It streamlines the way observable objects interact with the view hierarchy by automatically generating the boilerplate code you previously had to write when using the ObservableObject protocol. It simplifies the process of providing observable data to SwiftUI views while maintaining the same behavior as its predecessors.
With @Observable, the macro generates source code at compile time, allowing developers to focus on their view models and avoid the verbosity of declaring explicit properties inside their observable classes.
The observation framework in SwiftUI relies on @Observable to automatically track state changes in your objects and notify the view hierarchy about new values. This makes view updates more efficient and ensures that your data stays in sync with the UI.
The observable macro takes over from the ObservableObject protocol, making it easier to define observable properties in your view model. Unlike older approaches where you had to mark each published property explicitly, @Observable minimizes repetitive code.
For example, consider a view model that tracks a user’s profile information:
1import Observation 2 3@Observable 4class UserProfile { 5 var name: String = "John Doe" 6 var age: Int = 30 7}
Here, the observable macro automatically generates the necessary source code for observing mutable properties such as name and age.
To use @Observable, start by creating an observable class or observable object using the @Observable keyword. Then, define the properties you want to track.
1import SwiftUI 2import Observation 3 4@Observable 5class CounterViewModel { 6 var count: Int = 0 7}
You can then use this observable class in your SwiftUI view to create bindings and trigger view updates automatically.
1struct ContentView: View { 2 @StateObject private var viewModel = CounterViewModel() 3 4 var body: some View { 5 VStack { 6 Text("Count: \(viewModel.count)") 7 Button("Increment") { 8 viewModel.count += 1 9 } 10 } 11 } 12}
This integration ensures the view body refreshes whenever the value of viewModel.count changes.
You can use the environment key to provide observable data to multiple views in the view hierarchy. This makes it easier to share state without passing instances explicitly.
1struct ParentView: View { 2 @Environment(\.viewModel) var viewModel: CounterViewModel 3 4 var body: some View { 5 ChildView() 6 } 7} 8 9struct ChildView: View { 10 @Environment(\.viewModel) var viewModel: CounterViewModel 11 12 var body: some View { 13 Button("Increment") { 14 viewModel.count += 1 15 } 16 } 17}
This ensures consistent state across child views, improving code readability and maintainability.
The observable protocol allows developers to further customize their observable objects, offering flexibility in managing data and state changes.
• Improved App's Performance: Automatically generated source code reduces overhead and ensures optimized state changes.
• Simplified Syntax: The new macro eliminates the need for explicitly declaring published properties.
• Scalable View Hierarchy: Easily share observable objects across multiple views using the environment key.
• Clearer Implementation Details: Minimizes verbosity and makes your Swift-specific implementation cleaner.
If you’ve been using ObservableObject protocol with @Published, migrating to @Observable is straightforward. Simply replace the observable object definitions with the observable macro. The new property wrapper will handle the same behavior with less code.
1// Before 2class CounterViewModel: ObservableObject { 3 @Published var count: Int = 0 4} 5 6// After 7@Observable 8class CounterViewModel { 9 var count: Int = 0 10}
• Always import Observation to access the observation framework.
• Use observable properties judiciously to avoid unnecessary state changes.
• Keep your view model logic separate from the view struct for better maintainability.
With Swiftui Observable, managing state changes and observable data in SwiftUI views is simpler and more efficient. By leveraging the observable macro and observation framework, you can write cleaner, more maintainable source code that scales seamlessly with your app. Start exploring the power of @Observable in your projects today and experience the difference in app's performance firsthand!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.