Created
February 3, 2023 16:13
-
-
Save pteasima/41aff352925a01895b308cf95a82c1a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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