Logo for tanaschita.com

The @Environment property wrapper in SwiftUI

Learn how to share global data between SwiftUI views

12 Mar 2021 · 2 min read

With the @Environment property wrapper, SwiftUI provides a possibility to share data between views without explicitly passing the data from view to view. By setting an environment property on a view, it will be available not only in the view itself but also in all of its subviews.

SwiftUI provides predefined values that we can use just out of the box like colorScheme, managedObjectContext, timeZone, openURL and more.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

For example, we can access the current color scheme in our view by using the colorScheme property.

struct ContentView: View {
@Environment(\.colorScheme) private var colorScheme
var body: some View {
VStack {
Text(colorScheme == .dark ? "dark" : "light")
}
}
}

A full list is available at Apple's EnvironmentValues documentation.

If you like to create your own @Environmentvalues, check out this article on How to create custom @Environment values in SwiftUI.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

swift

ios

Understanding basic animations in SwiftUI

Learn different options to animate SwiftUI views.

16 Jan 2023 · 4 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum