@EnvironmentObject

Опубликовано: 15 Январь 2025
на канале: Swift++
93
7

EnvironmentObject in Swift is a powerful feature for sharing data across multiple views without the need to pass it through each view's initializer. In this example, we created a shared UserProfile class as an ObservableObject. This class holds user data like name and age. We then injected this UserProfile into the SwiftUI environment at the app's root level using environment object. This makes UserProfile accessible to any child view in the view hierarchy. This approach simplifies the data flow, especially in complex apps with multiple views needing access to the same data.