Skip to main content

How to create and use custom environment values

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create and use custom environment values 관련

SwiftUI by Example

Back to Home

How to create and use custom environment values | SwiftUI by Example

How to create and use custom environment values

Updated for Xcode 16

Improved in iOS 18

SwiftUI's @Entry macro makes it straightforward to create custom values for the environment, although I'd recommend you also add a View extension to make your code clearer.

The first step is to make an extension on EnvironmentValues, using @Entry inside there to create your custom environment key, give it a type, and also give it a default value:

extension EnvironmentValues {
    @Entry var iconColor: Color = .red
}

The @Entry macro automatically turns that into a fully fledged environment key and value, meaning that we can now use environment(\.iconColor, .blue) to set a value, and @Environment(\.iconColor) to read that value back out, like this:

struct BubblesView: View {
    @Environment(\.iconColor) var iconColor

    var body: some View {
        Image(systemName: "bubbles.and.sparkles.fill")
            .foregroundStyle(iconColor)
            .font(.largeTitle)
    }
}

struct ContentView: View {
    var body: some View {
        HStack {
            BubblesView()
                .environment(\.iconColor, .blue)

            BubblesView()
                .environment(\.iconColor, .red)
        }
    }
}
Similar solutions…
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
Observable objects, environment objects, and @Published | SwiftUI by Example

Observable objects, environment objects, and @Published
What is the @Environment property wrapper? | SwiftUI by Example

What is the @Environment property wrapper?
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts

이찬희 (MarkiiimarK)
Never Stop Learning.