how to use Environment in SwiftUI

Asked on 06/18/2025

1 search

In SwiftUI, the Environment is a powerful feature that allows you to pass data down the view hierarchy without having to pass it explicitly through each view. This is particularly useful for global settings or data that many views need access to, such as color schemes, locale settings, or custom data.

To use the Environment in SwiftUI, you typically use the @Environment property wrapper to access environment values within a view. Here's a basic example:

import SwiftUI

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

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

In this example, the @Environment property wrapper is used to access the current colorScheme of the app, which can be either .light or .dark. The text color is then set based on the current color scheme.

For more advanced usage, you can define your own environment keys and values. This involves creating a custom key by conforming to the EnvironmentKey protocol and then extending the EnvironmentValues to include your custom key.

If you're interested in learning more about how environment updates work in SwiftUI, you might find the session Optimize SwiftUI performance with Instruments (19:54) helpful. This session discusses how environment updates are handled and how they affect view updates in SwiftUI.