Created
August 22, 2025 08:58
-
-
Save abhi21git/fccc76aac960229f7e9ffcadfb6a7570 to your computer and use it in GitHub Desktop.
Use if condition on SwiftUIView without breaking method chaining
This file contains hidden or 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
| extension View { | |
| @ViewBuilder | |
| func `if`<TrueContent: View, FalseContent: View>( | |
| _ condition: Bool, | |
| @ViewBuilder _ trueTransform: (Self) -> TrueContent, | |
| @ViewBuilder else falseTransform: (Self) -> FalseContent | |
| ) -> some View { | |
| if condition { | |
| trueTransform(self) | |
| } else { | |
| falseTransform(self) | |
| } | |
| } | |
| } | |
| // Usage: - | |
| struct ContentView: View { | |
| let isSelected: Bool = true | |
| var body: some View { | |
| Text("Hello, world!") | |
| .if(isSelected) { | |
| $0.foregroundColor(.primary) | |
| } else: { | |
| $0.foregroundColor(.secondary) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment