popToRootViewController in SwiftUI

What is the best practice to achieve popToRootViewController like functionality in SwiftUI? There are couple of ways to do it and one of them is described nicely here (https://stackoverflow.com/questions/57334455/swiftui-how-to-pop-to-root-view) via publish event but it losses the animation while popping to root. Please suggest.

同问,有没有好的解决办法?
we used the approach with navigation links. Alternatively, you can open the flow in a sheet and close the sheet altogether.

With iOS 16, you can now use NavigationStack. You can use the NavigationPath variable in NavigationStack in order to take control over the stack of views you have pushed and popped.

NavigationPath allows you to create a type-erasing variable to keep track of your views, but it is easy to create one with any type, like below, where I use an array of Strings.

struct ContentView : View {
    @State private var path: [String]
    var body: some View {
        NavigationStack(path: $path){
            List{
                NavigationLink("title", value: "nextView")
            }
            .navigationDestination(for: String.self){ str in
                DetailView(strToShow: str)
            
            }
        } 
        
    }
   
}

Each NavigationLink will pass a value to the .navigationDestination modifier and will add the view to the path variable. Then, at any point in time, you can call path.popLast() to go backwards by one view, or set the path back to an empty array like this: path = []. This will pop you to the first page. This can be called in a matter of ways, for instance you can add a button to the toolbar that does this.

popToRootViewController in SwiftUI
 
 
Q