Skip to main content

environment_keys

Macro environment_keys 

Source
macro_rules! environment_keys {
    ($(
        $(#[$meta:meta])*
        $name:ident : $ty:ty = $default:expr
    ),* $(,)?) => { ... };
}
Expand description

Declare environment keys of your own.

A key is inherently a global: one name is one EnvironmentKey conformance and one key path, minted once and shared by everything that reads or writes it. So the declaration is a static — and writing that by hand was the noisiest thing in this crate:

ⓘ
static KEY: OnceLock<&'static CustomEnvKey<String>> = OnceLock::new();
let key = *KEY.get_or_init(|| Box::leak(Box::new(env_key("greeting", "hello".to_string()))));

This says the same thing in one line per key:

environment_keys! {
    /// How deeply this row is nested.
    depth: i64 = 3,
    /// What to greet the reader with.
    greeting: String = "hello",
}

text("hi").environment_value(depth(), 7).environment_value(greeting(), "bonjour")

Each entry becomes a function returning the one key, so depth() in two places is one key in both. Reading one is EnvironmentValues::value_for, which is typed by the key and so cannot be read as the wrong thing.

The name SwiftUI sees includes the declaring module, so two modules may each have a depth without colliding — a key is shared by calling the same function, not by agreeing on a string.