Skip to content

Instantly share code, notes, and snippets.

@abhi21git
Created August 22, 2025 08:58
Show Gist options
  • Save abhi21git/fccc76aac960229f7e9ffcadfb6a7570 to your computer and use it in GitHub Desktop.
Save abhi21git/fccc76aac960229f7e9ffcadfb6a7570 to your computer and use it in GitHub Desktop.
Use if condition on SwiftUIView without breaking method chaining
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