Skip to content

Instantly share code, notes, and snippets.

@pteasima
Created February 3, 2023 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pteasima/41aff352925a01895b308cf95a82c1a2 to your computer and use it in GitHub Desktop.
Save pteasima/41aff352925a01895b308cf95a82c1a2 to your computer and use it in GitHub Desktop.
import SwiftUI
import Dependencies
struct Foo: DependencyKey {
static var liveValue: Self {
.init {
"foo"
}
}
var foo: () -> String
}
extension DependencyValues {
var foo: Foo {
get { self[Foo.self] }
set { self[Foo.self] = newValue }
}
}
extension DependencyValues {
var bar: Bar {
get { self[Bar.self] }
set { self[Bar.self] = newValue }
}
}
struct Bar: DependencyKey {
static var liveValue: Self {
@Dependency(\.foo) var foo
return .init {
return foo.foo()
}
}
var bar: () -> String
}
struct DependenciesPlayground_Previews: View, PreviewProvider {
static var previews: some View {
VStack {
self.init()
withDependencies {
$0.foo.foo = { "baz" }
} operation: {
Group {
self.init()
withDependencies {
$0.bar = .liveValue
$0.foo = .liveValue
} operation: {
Group {
self.init()
withDependencies {
$0.bar = .liveValue
} operation: {
self.init()
}
}
}
}
}
}
}
@Dependency(\.foo) private var foo
@Dependency(\.bar) private var bar
var body: some View {
VStack {
Text(foo.foo())
Text(bar.bar())
Text("---")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment