In SwiftUI there\'s frequently a need to display an \"empty\" view based on some condition, e.g.:
struct OptionalText:
You can use the @ViewBuilder. Then you don't even need an EmptyView
:
@ViewBuilder
var body: some View {
if let text = text {
Text(text)
}
}
Note than you don't return anything, with a @ViewBuilder
you just build your view.
You have to return something. If there is some condition where you want to display nothing, "display" an...EmptyView
;)
var body: some View {
Group {
if text != nil {
Text(text!)
} else {
EmptyView()
}
}
}
The SwiftUI DSL will require you to wrap the if/else in a Group
and the DSL has no guard/if let nomenclature.
As of Xcode 12 beta 2 the Group
view is no longer needed and if let
declarations are supported, so the resulting body
can be a bit more succint:
var body: some View {
if let text = text {
Text(text)
} else {
EmptyView()
}
}