NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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)
    }
}

   

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.

3      

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

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started 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.