What does @environment do in swiftui

Asked on 08/05/2024

1 search

In SwiftUI, the @Environment property wrapper is used to read values from the environment. The environment is a collection of values that are shared across the view hierarchy, such as user settings, system settings, or custom values that you define. By using @Environment, you can access these values in your views without having to pass them explicitly through the view hierarchy.

For example, you might use @Environment to access the current color scheme (light or dark mode) or to read the current locale for localization purposes.

Here's a simple example of how @Environment might be used:

struct ContentView: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        Text("Hello, World!")
            .foregroundColor(colorScheme == .dark ? .white : .black)
    }
}

In this example, the colorScheme environment value is accessed to determine the text color based on whether the app is in dark mode or light mode.

For more detailed information on SwiftUI and its capabilities, you can refer to the session SwiftUI essentials from WWDC 2024.