Environment

  • Environment is a container for values to be passed down an element tree.

    Environment values are not resolved until the tree is being rendered, so they do not need to be explicitly passed to elements at the time they are created.

    Environment key-value pairs are strongly typed: keys are types conforming to the EnvironmentKey protocol, and each key’s value is the type of that key’s EnvironmentKey.Value associated value. Keys must provide a default value.

    Example

    To set an environment value, so that it will cascade to child elements, use AdaptedEnvironment. Here, every element in childElement will have access to someValue via the key MyEnvironmentKey.

    AdaptedEnvironment(
        key: MyEnvironmentKey.self,
        value: someValue,
        wrapping: childElement
    )
    

    To read an environment value, use EnvironmentReader. If this element were part of the child element in the previous example, myValue would be set to someValue. If the key had not been set in an ancestor element, the value would be MyEnvironmentKey.defaultValue.

    struct MyElement: ProxyElement {
        var elementRepresentation: Element {
            return EnvironmentReader { environment -> Element in
                let myValue = environment[MyEnvironmentKey.self]
                return SomeElement(using: myValue)
            }
        }
    }
    
    See more

    Declaration

    Swift

    public struct Environment
  • Types conforming to this protocol can be used as keys in an Environment.

    Using a type as the key allows us to strongly type each value, with the key’s EnvironmentKey.Value associated value.

    Example

    Usually a key is implemented with an uninhabited type, such an empty enum.

    enum WidgetCountKey: EnvironmentKey {
        static let defaultValue: Int = 0
    }
    

    You can write a small extension on Environment to make it easier to use your key.

    extension Environment {
        var widgetCount: Int {
            get { self[WidgetCountKey.self] }
            set { self[WidgetCountKey.self] = newValue }
        }
    }
    
    See more

    Declaration

    Swift

    public protocol EnvironmentKey