How we can use alert menu before delete list items in SwiftUI?

I have list items in SwiftUI, and when I delete list items, but when I click the delete button, it delete item randomly, I want to delete seleted item, where is the mistake?

struct MyView: View {

   @State private var selectedUsers: MyModel?
   @State var datas: [MyModel]
   @State private var confirmDelete = false

    var body: some View {
        
            ScrollView(.vertical, showsIndicators: false, content: {
                
                VStack(content: {
                    
                    ForEach(datas){ data in
  
                        MyRowView(data: data)
                         
                            .contextMenu {

                                Button(action: {
                                    self.delete(item: data)
                                }) {
                                    Text("delete") 
                                }
                               
                            }
                            .onTapGesture {
                                selectedUsers = data
                            
                            }
                          .confirmationDialog( "Are you sure ?",
                  isPresented: $confirmDelete,
                  titleVisibility: .visible
                ){
                   
                  Button(role: .destructive) {
                    self.delete(item: data)
                  } label: {
                    Text("ok")
                     
                  }

                  Button(role: .cancel) {
                     
                  } label: {
                    Text("cancel")
                     
                  }
                }
           
                    } .onDelete { (indexSet) in
                       self.datas.remove(atOffsets: indexSet)
                    }})
           })}

    private func delete(item data: MyModel) {
               if let index = datas.firstIndex(where: { $0.id == data.id }) {
                   datas.remove(at: index)
               }
           }}

I'm not sure to understand the logic.

You delete (onDelete), whatever answer you give.

I would do it differently:

  • create a func to be called in onDelete
  • call the confirmation alert there
  • only execute delete in OK action

Have a look here: https://www.hackingwithswift.com/books/ios-swiftui/deleting-items-using-ondelete

How we can use alert menu before delete list items in SwiftUI?
 
 
Q