Created
June 29, 2024 11:54
-
-
Save simonnickel/98091efcc33b052cc1932a8e90654012 to your computer and use it in GitHub Desktop.
Swift 6: SwiftUI Environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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