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

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.