Working with environment variables
A view that works directly with an observed object is a common use case. For example, a view can work with a ViewModel
class or have a SwiftData query that fetches data models from the persistent store.
However, there are cases where we have an observed object shared across different views.
Some examples of such a use case are as follows:
- App settings: The user profile is part of app settings and can be stored in an environment variable
- Themes and styling: Primary color tint font style, spaces, and more
- User authentication state: The login state is a good example of an environment variable
Sharing the same object down a view hierarchy can be cumbersome, but SwiftUI offers a helpful feature known as environment variables. While environment variables aren’t a recent addition to iOS (they have been available before iOS 17), the Observation framework provides comprehensive support.
There are two ways of adding an...