How it works
TableColumn describes a single column of a Table, pairing a header with a rule for producing each row's cell from the table's underlying data. You declare one TableColumn per field you want to display, and the table draws the rows by applying each column to every element in its collection. Reach for it whenever you need to present a collection of structured records as a sortable, multi-column grid rather than a flat list.
Declare columns inside a Table's content builder
A
Tabletakes its columns from a closure built with the@TableColumnBuilderresult builder, so you list eachTableColumnin sequence as the table's content. HereTable(people)opens that builder and the twoTableColumnentries become the grid's columns, in order, left to right.Give each column a header with the title initializer
The first argument to
TableColumnis the column's header label, supplied as a string. The two columns are titled"Name"and"Role", and those strings render as the header row above their respective cells.Bind a column to a property with the value key path
The
value:parameter takes aKeyPathfrom a row element to aComparableproperty; the table reads that property for every row to fill the column's cells and to know how to sort by it.TableColumn("Name", value: \.name)projects eachPerson'sname, and\.roleprojects itsrole— no per-cell view code required because both properties are strings.Let the row type drive the column's data
Each
TableColumnresolves its key path against the element type of the table's collection, so the row type must beIdentifiablefor the table to track rows. ThePersonstruct conforms toIdentifiablevia itsid, and\.name/\.roleare key paths into that samePerson, which is why the columns line up with thepeoplearray.
TableColumn("ID", value: \.id.uuidString) after the "Role" column to see a new column appear and the row data flow through it.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 TableColumnDemo: View {
struct Person: Identifiable {
let id = UUID()
let name: String
let role: String
}
let people = [
Person(name: "Ada Lovelace", role: "Engineer"),
Person(name: "Alan Turing", role: "Scientist"),
Person(name: "Grace Hopper", role: "Admiral")
]
var body: some View {
Table(people) {
TableColumn("Name", value: \.name)
TableColumn("Role", value: \.role)
}
.padding()
}
}