'SwiftUI dismissing view by setting NavigationLink tag to nil

I'm trying to implement the logic of programmatic view pop in SwiftUI

I set a tag on the items and create a corresponding variable for the selected item, but when I click the button on the DetaiView screen, nothing happens.

The problem disappears if I use VStack instead of List or use the presentationMode Environment variable to release the screen, but I'd like to use List.

Code:

struct ContentView: View {
    
    @State var data: [Int] = [1, 2, 3, 4, 5]
    @State var selectedItem: Int? = nil
    
    var body: some View {
        NavigationView {
//            NavigationLink( // This make dismiss work
//                destination: DetailView(selectedItem: $selectedItem),
//                tag: 123,
//                selection: $selectedItem,
//                label: { Text("\(123)") }
//            )
            List { // VStack here make dismiss work
                ForEach(data, id: \.self) { element in
                    NavigationLink(
                        destination: DetailView(selectedItem: $selectedItem),
                        tag: element,
                        selection: $selectedItem,
                        label: { Text("\(element)") }
                    )
                    .isDetailLink(false)
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var selectedItem: Int?
//    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View {
        VStack {
            Text("DETAIL")
            Button("BUTTON") {
                selectedItem = nil // Variable set to nil but nothing happens
//                presentationMode.wrappedValue.dismiss()
            }
        }
    }
}

Am I doing something wrong or is it a SwiftUI bug?

Thank you!



Solution 1:[1]

Update: Fixed

Tested with Xcode 13.3 / iOS 15.4

Demo with just copy-pasted code:

demo

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