Skip to content

Instantly share code, notes, and snippets.

@stormychel
Created September 23, 2024 03:02
Show Gist options
  • Save stormychel/91ddb46a529526150a7b2d2b41491815 to your computer and use it in GitHub Desktop.
Save stormychel/91ddb46a529526150a7b2d2b41491815 to your computer and use it in GitHub Desktop.
Conditionally Display SwiftUI View Based on a Boolean
extension View {
/// Conditionally displays the view based on the provided Boolean condition.
///
/// This modifier allows you to show or hide a view depending on the value of `condition`.
/// If `condition` is `true`, the view is displayed as is.
/// If `condition` is `false`, the view is replaced by an `EmptyView`, which effectively removes it from the layout.
///
/// - Parameter condition: A Boolean value that determines whether the view should be displayed. If `true`, the view is shown; if `false`, it is hidden.
/// - Returns: Either the view itself, or an `EmptyView` if the condition is `false`.
///
/// - Example:
/// ```
/// Text("Hello, World!")
/// .if(someCondition)
/// ```
///
/// - Author: [Michel Storms - [email protected]]
@ViewBuilder
func `if`(_ condition: Bool) -> some View {
if condition {
self
} else {
EmptyView()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment