Delete List item with SwiftUI

Learn how to easily delete an item from a List view using SwiftUI

Delete List item with SwiftUI

This is going to be a really quick tutorial because SwiftUI makes deleting a list item super simple.

Step 1: Create data source

Update your ContentView to look like this:

struct ContentView: View {
    @State var listItems = ["Item 1", "Item 2", "Item 3"]
    
    var body: some View {
        Text("Hello World")
    }
}

We now have our data source. Because this has a State property wrapper, the list will update when changes happen to listItems.

Step 2: Add the List view

Replace the Hello World Text view with the following:

List {
    ForEach(listItems, id: \.self) { (item) in
        Text(item)
    }
}

You should now be able to run the app and see items in the list.

Step 3: Add onDelete method

Update the list to look like this:

List {
    ForEach(listItems, id: \.self) { (item) in
        Text(item)
    }.onDelete { (indexSet) in
        self.listItems.remove(atOffsets: indexSet)
    }
}

All we done was add the onDelete to each item in our list. The onDelete takes an IndexSet as its argument. We can use the indexSet argument to remove the correct item from our listItems array.

To remove it from listItems we call the remove method on the listItems and we pass through the indexSet.

Step 4: Clean-up

This is not required because the closure that we use for onDelete is small, but if we had other logic when deleting, it would be better for this to be in a separate method.

Create a new method called deleteItem below the body property:

private func deleteItem(at indexSet: IndexSet) {
    self.listItems.remove(atOffsets: indexSet)
}

We can now call the deleteItem method from onDelete. To do that, update the onDelete that we add previously to look like this:

.onDelete(perform: self.deleteItem)

And that is it, if you build and run the app you should be able to delete items from the List view.

Final source code

struct ContentView: View {
    @State var listItems = ["Item 1", "Item 2", "Item 3"]
    
    var body: some View {
        List {
            ForEach(listItems, id: \.self) { (item) in
                Text(item)
            }.onDelete(perform: self.deleteItem)
        }
    }
    
    private func deleteItem(at indexSet: IndexSet) {
        self.listItems.remove(atOffsets: indexSet)
    }
}