Peter
Peter

Reputation: 922

SwiftUI and EmptyViews

I have the following code example:

struct ContentView: View {
    @State var showText = true

    var body: some View {
        VStack {
            if self.showText {
                Text("Hello")
            }
            //else {
            //      EmptyView()
            //  }
        }
    }
}

When it runs I get the text showing as normal. However, if I set showText to false it still compiles and runs as normal even though the VStack contains nothing - it just doesn't show anything when run. If I uncomment the else clause the example also runs as expected. If I remove all the contents of the VStack however, the example won't compile as nothing is returned.

So my questions are:

Is SwiftUI silently adding an EmptyView when nothing is in the VStack when showText is false ?

Should I really be adding the else clause and return an EmptyView ?

The question isn't completely academic either as I have a use case where I would prefer the whole view to be more or less 'thrown away' rather than have EmptyViews in the hierarchy, though my understanding of SwiftUI is pretty limited at the moment so it may not matter.

Upvotes: 1

Views: 2859

Answers (1)

Josh Homann
Josh Homann

Reputation: 16327

VStack is a function builder so it expects to get some value back from the closure. In the case of the if it invokes the buildEither version of the function builder so that satisfies the condition that its not empty. See the function builder proposal. Any ways you should not worry about the EmptyViews. A SwiftUI.View is just a blue print to build the actual view (as apple calls it a cheap value on the stack). It is not the real view object in memory and on the graphics card, as with a UIView or CALayer. The rendering system is going to translate your EmptyView into a noop. SwiftUI.Views get created and discarded all the time and are designed to be cheap unlike UIViews, and the system diff's the SwiftUI.View tree and only applies the delta to the real views in graphics memory similarl to how Flutter, React, and Android Compose work.

Upvotes: 5

Related Questions