UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 37 – Project 7, part 2 - Deleting any row seems to work

Forums > 100 Days of SwiftUI

I was working through the first part of this task, "Building a list we can delete from", and after creating the sample list with the ability to add and delete "Test" items, I expected that when swiping to delete an item that always the last one would be deleted, rather than the one I was swiping (as showing in the video). However I found I was able to swipe and delete specific rows correctly, without having to add an id property to the ExpenseItem class. This is my code:

struct ExpenseItem {

    let name: String

    let type: String

    let amount: Int
}

class Expenses: ObservableObject {

    @Published var items = [ExpenseItem]()

}

struct ContentView: View {

    @ObservedObject var expenses = Expenses()

    var body: some View {

        NavigationView {

            List {

                ForEach(expenses.items, id: \.name) { item in

                    Text(item.name)
                }
                .onDelete(perform: { indexSet in

                    self.removeItems(at: indexSet)
                })
            }
            .listStyle(PlainListStyle())
            .navigationBarTitle("iExpense")
            .navigationBarItems(trailing:

                Button(action: {

                    let expense = ExpenseItem(name: "Test", type: "Test Type", amount: 1)
                    self.expenses.items.append(expense)

                }, label: {

                    Image(systemName: "plus")
                })
            )
        }
    }

    func removeItems(at offsets: IndexSet) {

        self.expenses.items.remove(atOffsets: offsets)
    }
}

Has anything changed in SwiftUI since this was published so that it no longer necessary to add an id property to a class used in a list like this, or to conform to the Identifiable protocol? Or have I overlooked something in my code?

For reference I'm using XCode 12.5 and running on an iOS 14.5 simulator

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.