TechnologiesSwiftUI

Table struct

iOSmacOStvOSwatchOSvisionOS✓ renders

A container that presents rows of data arranged in one or more columns,

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.

  1. Feed the rows to Table(_:)

    The initializer takes the collection that supplies one row per element. Its elements must conform to Identifiable so the table can track them across updates, which is why Purchase declares an id. Here Table(purchases) drives the table from the purchases array.

  2. Declare columns with TableColumn

    Inside the trailing column builder you list a TableColumn for 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", ...) and TableColumn("Price", ...).

  3. 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 the item string from each Purchase, while value: \.price reads the price, so the table maps the same field across all rows automatically.

  4. Place and size the table in the layout

    Table is itself a View, 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 of body.

Try it — Add a third row, 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.

Table.swift
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()
    }
}
Live preview
Item Price Coffee $4.50 Bagel $3.25 Notebook $12.00
Item Price Coffee $4.50 Bagel $3.25 Notebook $12.00
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →