How to delete a row from a table

To display rows and columns of data in a nice layout like a spreadsheet I use a table like the code here ..

    Table(array) {
         TableColumn("Ticker", value: \\.ticker)
         TableColumn("Other", value: \.other)
     }

To delete a row from the table the advice is to use a ForEach loop. Since I don’t use a ForEach loop, how do I delete rows from the table ? With this code there is no way to attach a .onDelete modifier or a Button

Any advice would be much appreciated

Thank you

Welcome to the forum.

  • array is the data source.

  • So if you remove an item in array, the table should update automatically.

Here a very basic example

struct Customer: Identifiable {
    let id = UUID()
    let name: String
    let email: String
}

struct ContentView: View {
    @State var customers =
    [Customer(name: "John Smith",
              email: "john.smith @ example.com"),
     Customer(name: "Jane Doe",
              email: "jane.doe @ example.com"),
     Customer(name: "Bob Johnson",
              email: "bob.johnson @ example.com")]
    
    var body: some View {
        Table(customers) {
            TableColumn("name", value: \.name)
            TableColumn("email", value: \.email)
            
        }
        Button("Remove Jane Doe") {
            customers.removeAll(where: { $0.name == "Jane Doe"} )
        }

    }
}

See details here: https://developer.apple.com/documentation/swiftui/table

PS: you have a typo with the double backslash:

\\.ticker

If that answers your question, don't forget to close the thread by marking the answer as correct.

How to delete a row from a table
 
 
Q