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

Viewed 374

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
        }
    }
}



3 Answers

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

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

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)
    }
}
Related