Last active
February 16, 2024 13:22
-
-
Save magnuskahr/60dcffc18d1f04ac589dd597d188b103 to your computer and use it in GitHub Desktop.
SwiftUI ViewRoot unable to change environment
This file contains 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
// 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