Created
June 29, 2024 12:51
-
-
Save simonnickel/1324004f1819d0b4869fc493521f7c61 to your computer and use it in GitHub Desktop.
Swift 6: SwiftUI Environment - nonisolated init with Non Sendable param
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 | |
protocol DependencyValue { | |
var content: String { get } | |
} | |
@MainActor class Dependency { | |
var value: DependencyValue // NonSendable | |
nonisolated init(value: sending DependencyValue? = nil) { | |
self.value = value ?? Value(content: "initial") | |
setupValue(value ?? Value(content: "initial")) | |
} | |
func setupValue(_ value: sending DependencyValue) { | |
self.value = value | |
} | |
class Value: DependencyValue { | |
init(content: String) { | |
self.content = content | |
} | |
let content: String | |
} | |
} | |
// MARK: Entry | |
extension EnvironmentValues { | |
@Entry var dependencyEntry = Dependency(value: Dependency.Value(content: "@Entry")) | |
} | |
// MARK: EnvironmentValues | |
struct DependencyKey: EnvironmentKey { | |
static let defaultValue = Dependency(value: Dependency.Value(content: "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