Skip to content

Instantly share code, notes, and snippets.

@malhal
Last active March 10, 2025 22:47
Show Gist options
  • Save malhal/4b11049f85425e272d4897bd125cafeb to your computer and use it in GitHub Desktop.
Save malhal/4b11049f85425e272d4897bd125cafeb to your computer and use it in GitHub Desktop.
import SwiftUI
extension EnvironmentValues {
@Entry var counter = Binding.constant(0)
@Entry var inc = {}
}
struct ContentView: View {
@State private var counter = 0
var body: some View {
VStack {
Text("Counter \(counter)")
ContentView2()
}
.font(.title3)
.buttonStyle(.borderedProminent)
.environment(\.counter, $counter)
.environment(\.inc) {
counter += 1
}
}
}
struct ContentView2: View {
var body: some View {
ContentView3()
}
}
struct ContentView3: View {
@Environment(\.counter) private var counter
@Environment(\.inc) private var inc
var body: some View {
Button("Binding Increment") {
counter.wrappedValue += 1
}
Button("Closure Increment") {
inc()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment