GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Delete List Rows

Forums > SwiftUI

Hi All. I am trying to add code to delete rows in a list, however, when I add the func "delete" to the ContentView, I get the following error message: "Cannot use mutating member on immutable value: 'self' is immutable". Below is the code used to create the list. Not sure what I am doing wrong here. Thanks for your help.

struct Cafe: Identifiable {
    var id = UUID()
    var name: String
    var image: String
}

struct ListRow: View {
    var cafe: Cafe

    var body: some View {
        HStack {
            Image(cafe.image)
                .resizable()
                .frame(width: 40, height: 40)
                .cornerRadius(5)
            Text(cafe.name)
        }
    }
}

struct ContentView: View {
    var cafes = [
        Cafe(name: "Cafe One", image: "one"),
        Cafe(name: "Cafe Two", image: "two"),
        Cafe(name: "Cafe Three", image: "three"),
        Cafe(name: "Cafe Four", image: "four"),
        Cafe(name: "Cafe Five", image: "five")
    ]

    var body: some View {
        NavigationView {
            List {
                ForEach (cafes) { cafe in
                    ListRow(cafe: cafe)
                }
                .onDelete(perform: delete)
            }
        }
    }

    func delete(at offsets: IndexSet) {
        cafes.remove(atOffsets: offsets)
    }
}

3      

Try adding @State to the cafes variable:

@State var cafes = [

This way you inform SwiftUI the variable can be mutated and needs to be observed to trigger view layout changes.

6      

Thanks for the help. I forgot all about @State.

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.

Save your spot

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.