Why list items not able to delete in SwiftUI?

I have a simple app in SwiftUI, and I try to delete list items in app , project is working, but still list items not able to delete, I do not know what I did not put in my codes, any idea will be appreciated.

struct MyView: View {

    @State private var selectedUsers: MyModel?
 
    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
                            
                            }
                        
                    } .onDelete { (indexSet) in
                        selectedUsers.remove(atOffsets: indexSet)
                    }})
           })}

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

model:

struct MyModel: Identifiable, Hashable, Codable {

    var id = UUID().uuidString
    var name: String
    }

  var datas = [
    
    MyModel(name: "david"),
    MyModel(name: "marry"),
  ]
Answered by Claude31 in 705967022

delete which one

If I understand correctly, in

                    } .onDelete { (indexSet) in
                        selectedUsers.remove(atOffsets: indexSet)
                    }})

you remove an item in selectedUsers. But you do not remove from datas.

Try to print selectedUsers and datas after remove and check what you get.

You should remove from dataSource (datas) as well in .onDelete.

Otherwise, you suppress in the list and it is immediately restored when rebuilding the list.

Accepted Answer

delete which one

If I understand correctly, in

                    } .onDelete { (indexSet) in
                        selectedUsers.remove(atOffsets: indexSet)
                    }})

you remove an item in selectedUsers. But you do not remove from datas.

Try to print selectedUsers and datas after remove and check what you get.

Could you post the complete project so that we can tell exactly what to do ?

Why list items not able to delete in SwiftUI?
 
 
Q