Skip to content

Instantly share code, notes, and snippets.

@Clarko
Created July 10, 2023 01:39
Show Gist options
  • Save Clarko/23c448c18b230e6922efc60dcc6ba079 to your computer and use it in GitHub Desktop.
Save Clarko/23c448c18b230e6922efc60dcc6ba079 to your computer and use it in GitHub Desktop.
Closures in the Environment
// replying to https://mastodon.world/@luckkerr/110684106839939474
import SwiftUI
struct MiscellaneousAction {
let action: () -> Void
init(_ action: @escaping () -> Void) {
self.action = action
}
func callAsFunction() {
action()
}
}
struct MiscActionKey: EnvironmentKey {
static var defaultValue: MiscellaneousAction = .init({})
}
extension EnvironmentValues {
var miscAction: MiscellaneousAction {
get { self[MiscActionKey.self] }
set { self[MiscActionKey.self] = newValue }
}
}
struct ContentView: View {
var body: some View {
ChildView()
.environment(\.miscAction, MiscellaneousAction {
print(Int.random(in: 0...999).formatted())
})
.tint(Color.random())
}
}
struct ChildView: View {
@Environment(\.miscAction) private var misc: MiscellaneousAction
var body: some View {
Button("Alphabet") { misc() }
.buttonStyle(.borderedProminent)
.bold(Bool.random())
.italic(Bool.random())
}
}
extension Color {
static func random() -> Self {
[.green, .yellow, .orange, .red, .purple, .blue].randomElement()!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment