What does @environment do in swiftui
Asked on 08/05/2024
1 search
In SwiftUI, the @Environment
property wrapper is used to read values from the environment. The environment is a collection of values that are shared across the view hierarchy, such as user settings, system settings, or custom values that you define. By using @Environment
, you can access these values in your views without having to pass them explicitly through the view hierarchy.
For example, you might use @Environment
to access the current color scheme (light or dark mode) or to read the current locale for localization purposes.
Here's a simple example of how @Environment
might be used:
struct ContentView: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
Text("Hello, World!")
.foregroundColor(colorScheme == .dark ? .white : .black)
}
}
In this example, the colorScheme
environment value is accessed to determine the text color based on whether the app is in dark mode or light mode.
For more detailed information on SwiftUI and its capabilities, you can refer to the session SwiftUI essentials from WWDC 2024.

Create custom visual effects with SwiftUI
Discover how to create stunning visual effects in SwiftUI. Learn to build unique scroll effects, rich color treatments, and custom transitions. We’ll also explore advanced graphic effects using Metal shaders and custom text rendering.

Get started with HealthKit in visionOS
Discover how to use HealthKit to create experiences that take full advantage of the spatial canvas. Learn the capabilities of HealthKit on the platform, find out how to bring an existing iPadOS app to visionOS, and explore the special considerations governing HealthKit during a Guest User session. You’ll also learn ways to use SwiftUI, Swift Charts, and Swift concurrency to craft innovative experiences with HealthKit.

What’s new in SwiftUI
Learn how you can use SwiftUI to build great apps for any Apple platform. Explore a fresh new look and feel for tabs and documents on iPadOS. Improve your window management with new windowing APIs, and gain more control over immersive spaces and volumes in your visionOS apps. We’ll also take you through other exciting refinements that help you make expressive charts, customize and layout text, and so much more.