跳转至
Structure

Environment

A property wrapper that reads a value from a view's environment.

Declaration

@frozen @propertyWrapper struct Environment<Value> : DynamicProperty

Overview

Use the Environment property wrapper to read a value stored in a view's environment. Indicate the value to read using an EnvironmentValues key path in the property declaration. For example, you can create a property that reads the color scheme of the current view using the key path of the colorScheme property:

@Environment(\.colorScheme) var colorScheme: ColorScheme
You can condition a view's content on the associated value, which you read from the declared property's wrappedValue. As with any property wrapper, you access the wrapped value by directly referring to the property:

if colorScheme == .dark { // Checks the wrapped value.
    DarkContent()
} else {
    LightContent()
}
If the value changes, SwiftUI updates any parts of your view that depend on the value. For example, that might happen in the above example if the user changes the Appearance settings.

You can use this property wrapper to read --- but not set --- an environment value. SwiftUI updates some environment values automatically based on system settings and provides reasonable defaults for others. You can override some of these, as well as set custom environment values that you define, using the environment(_:_:) view modifier.

For the complete list of environment values provided by SwiftUI, see the properties of the EnvironmentValues structure. For information about creating custom environment values, see the EnvironmentKey protocol.

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Instance Property

wrappedValue The current value of the environment property.


Initializer

init(_:) Creates an environment property to read the specified key path.