Skip to content

Instantly share code, notes, and snippets.

@bsorrentino
Last active January 18, 2023 14:10
Show Gist options
  • Save bsorrentino/52e0722046fccd14f0f2ac49587903aa to your computer and use it in GitHub Desktop.
Save bsorrentino/52e0722046fccd14f0f2ac49587903aa to your computer and use it in GitHub Desktop.
This extension lets us add the .if modifier to our Views and will only apply the modifiers we add if the condition is met.

SwiftUI Conditional

With this extension, we can add the .if() modifier to our View!

Example

struct ContentView: View {
    @State private var shouldAddShadow: Bool = true

    var body: some View {
        Text("Hello, world!")
            .if(shouldAddShadow) { view in
                view.shadow(color: .black, radius: 10, x: 0.0, y: 0.0)
            }
    }
}
import SwiftUI
// [Conditional modifier](https://designcode.io/swiftui-handbook-conditional-modifier)
extension View {
@ViewBuilder func `if`<Content: View>(_ condition: Bool, then transform: (Self) -> Content) -> some View {
if condition {
transform(self)
} else {
self
}
}
@ViewBuilder func `if`<Content: View>(_ condition: Bool, then transformThen: (Self) -> Content, else transformElse: (Self) -> Content ) -> some View {
if condition {
transformThen(self)
} else {
transformElse(self)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment