Skip to content

Instantly share code, notes, and snippets.

@simonnickel
Created June 29, 2024 11:54
Show Gist options
  • Save simonnickel/98091efcc33b052cc1932a8e90654012 to your computer and use it in GitHub Desktop.
Save simonnickel/98091efcc33b052cc1932a8e90654012 to your computer and use it in GitHub Desktop.
Swift 6: SwiftUI Environment
import SwiftUI
@MainActor class Dependency {
var value: String
nonisolated init(value: String? = nil) {
self.value = value ?? "Initial"
}
}
// MARK: Entry
extension EnvironmentValues {
@Entry var dependencyEntry = Dependency(value: "@Entry")
}
// MARK: EnvironmentValues
struct DependencyKey: EnvironmentKey {
static let defaultValue = Dependency(value: "EnvironmentValues")
}
extension EnvironmentValues {
var dependency: Dependency {
get { self[DependencyKey.self] }
set { self[DependencyKey.self] = newValue }
}
}
struct ContentView: View {
@Environment(\.dependency) var dependency
@Environment(\.dependencyEntry) var dependencyEntry
var body: some View {
VStack {
Text("Hello, \(dependencyEntry.value)")
Text("Hello, \(dependency.value)")
}
.padding()
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment