'How do I have an "empty view" in SwiftUI?

So I want to have a view which presents conditionally, depending on the state of my model. I understand how to do this if each case has a view to present, but how do I handle the case where I want to show no view in some cases?

For instance:

struct MyView: View {

    enum ViewState {
        case A, B, C
    }

    let state: ViewState

    var view: some View {
        switch state {
            case .A:
                Text("A State")
            case .B:
                Text("B State")
            case .C:
                // empty
        }
    }
}





Solution 1:[1]

You can to use EmptyView and (!) mark view property as a ViewBuilder, like in below finalised example:

struct MyView: View {

    enum ViewState {
        case A, B, C
    }

    let state: ViewState

    @ViewBuilder var view: some View {    // << here !!
        switch state {
            case .A:
                Text("A State")
            case .B:
                Text("B State")
            case .C:
                EmptyView()         // << here !!
        }
    }

    var body: some View { // replicated for demo
        self.view
     }
}

Tested with Xcode 13.2

Solution 2:[2]

You can use EmptyView() and mark you view with @ViewBuilder var view: some View

Solution 3:[3]

struct MyView: View {

    enum ViewState {
        case A, B, C
    }

    let state: ViewState

    var text: String {
        switch state {
            case .A:
               "A State"
            case .B:
                "B State"
            case .C:
                ""
        }
    }

    var view: some View {
       Text(text)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asperi
Solution 2
Solution 3 malhal