Removing SwiftUI View from hierarchy

In a UIKit application, removing a view from the hierarchy is straightforward—we simply call myView.removeFromSuperview(). This not only removes myView from the UI but also deallocates any associated memory.

Now that I'm transitioning to SwiftUI, I'm struggling to understand the recommended way to remove a view from the hierarchy, given SwiftUI's declarative nature.

I understand that in SwiftUI, we declare everything that should be displayed. However, once a view is rendered, what is the correct way to remove it? Should all UI elements be conditionally controlled to determine whether they appear or not?

Below is an example of how I’m currently handling this, but it doesn’t feel like the right approach for dynamically removing a view at runtime.

Can someone guide me on the best way to remove views in SwiftUI?

struct ContentView: View {
    @State private var isVisible = true

    var body: some View {
        VStack {
            if isVisible {  // set this to false to remove TextView?
                Text("Hello, SwiftUI!")
                    .padding()
            }

            Button("Toggle View") {
              ...
            }
        }
    }
}

I'm not sure you would need to remove a view.

I don't know how SwiftUI uses memory in the background, but views are drawn according to the state of the data. I've never had any memory issues with my SwiftUI apps.

So, in your example, the Text view would not be rendered when isVisible is false, and you don't need to do anything to make that happen. You don't need to do the SwiftUI equivalent of removeFromSuperview() (if there is such a thing), so you don't need to do:

if(!isVisible) {
    view.removeFromSuperview()
}
Removing SwiftUI View from hierarchy
 
 
Q