Image for post
Image for post

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

Image for post
Image for post

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

iOS developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store