Skip to content

Instantly share code, notes, and snippets.

@malhal
Last active May 15, 2025 17:46
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 {
@Binding(projectedValue: _counter) var counter
Button("Binding Increment") {
counter += 1
}
Button("Closure Increment") {
inc()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment