LAST CHANCE: Save 50% on all my Swift books and bundles! >>

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 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 July 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.