How it works
A table presents rows of data arranged in one or more columns, giving each value a labeled, aligned home that a list or stack can't express on its own. Reach for Table when your data is inherently tabular — records that share the same fields, such as the item and price of each purchase — and you want the framework to lay out headers, align cells, and keep columns in sync as rows change. You describe the shape of the data once, declare the columns, and Table handles the grid.
Feed the rows to Table(_:)
The initializer takes the collection that supplies one row per element. Its elements must conform to
Identifiableso the table can track them across updates, which is whyPurchasedeclares anid. HereTable(purchases)drives the table from thepurchasesarray.Declare columns with TableColumn
Inside the trailing column builder you list a
TableColumnfor each value you want to show. The first argument is the header title; the table draws it at the top of that column. The example declares two:TableColumn("Item", ...)andTableColumn("Price", ...).Bind each column to a property with a key path
The
value:parameter is a key path into the row element, telling the column which property to read and display in every cell.TableColumn("Item", value: \.item)pulls theitemstring from eachPurchase, whilevalue: \.pricereads theprice, so the table maps the same field across all rows automatically.Place and size the table in the layout
Tableis itself aView, so it participates in the normal modifier chain and expands to fill the space its container offers. Surrounding views are just where it plugs in — here.padding()insets the whole grid from the edges ofbody.
Purchase(item: "Tea", price: "$2.75"), to the purchases array and watch the table grow a new row without any change to the column declarations.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct TableDemo: View {
struct Purchase: Identifiable {
let id = UUID()
let item: String
let price: String
}
let purchases = [
Purchase(item: "Coffee", price: "$4.50"),
Purchase(item: "Bagel", price: "$3.25"),
Purchase(item: "Notebook", price: "$12.00")
]
var body: some View {
Table(purchases) {
TableColumn("Item", value: \.item)
TableColumn("Price", value: \.price)
}
.padding()
}
}