
Custom @Environment keys in SwiftUI
@Environment — is a property wrapper that allows any view access to global dependencies e.g Calendar, Locale, ColorScheme etc.
But what if we want to create our own global dependencies that are tight to our app domain. For example, we may want ImageFetcher
to be accessible for any view that can display remote images, so that images that were displayed on previous screens of our app would not need to be fetched again.
Turns out SwiftUI allows us to do this:
In order to achieve that we need to implement a couple of requirements.
EnvironmentKey
- requires us to provide a default value for our custom dependency.
The defaultValue
will be created when we first time access it via @Environment

By extending EnvironmentValues
we provide a property that we are going to use to access it via @Environment property wrapper.
Complete implemetation can be found here