Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Last active February 16, 2024 13:22
Show Gist options
  • Save magnuskahr/60dcffc18d1f04ac589dd597d188b103 to your computer and use it in GitHub Desktop.
Save magnuskahr/60dcffc18d1f04ac589dd597d188b103 to your computer and use it in GitHub Desktop.
SwiftUI ViewRoot unable to change environment
// Working with SwiftUI variadics, i need to set the environment of a child - which seems like is impossible.
// The spy always outputs "fail".
struct Transform<Content: View, Result: View>: View {
@ViewBuilder let content: Content
let transformation: (_VariadicView.Children.Element) -> Result
var body: some View {
_VariadicView.Tree(
Transformer(transformation: transformation)
) {
content
}
}
private struct Transformer: _VariadicView.UnaryViewRoot {
let transformation: (_VariadicView.Children.Element) -> Result
func body(children: _VariadicView.Children) -> some View {
ForEach(children) { child in
transformation(child)
}
}
}
}
struct TestKey: EnvironmentKey {
static var defaultValue: String = "fail"
}
struct TestKeySpy: View {
@Environment(\._testKey) private var value
var body: some View {
Text(value)
}
}
extension EnvironmentValues {
var _testKey: String {
get { self[TestKey.self] }
set { self[TestKey.self] = newValue }
}
}
// Test using the following:
Transform {
TestKeySpy()
} transformation: {
$0.environment(\._testKey, "success")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment