Apple Developer Documentation

Create and configure cells for your table dynamically using a data source object, or provide them statically from your storyboard.

Overview

Table views are data-driven elements of your interface. You provide your app’s data, along with the views needed to render each piece of that data onscreen, using a data source object—that is, an object that adopts the UITableViewDataSource protocol. The table view arranges your views onscreen and works with your data source object to keep that data up to date.

Table views organize your data into rows and sections. Rows display individual data items, and sections group related rows together. Sections are not required, but they are a good way to organize data that is already hierarchical. For example, the Contacts app displays the name of each contact in a row, and groups rows into sections based on the first letter of the person’s last name.

Provide the Numbers of Rows and Sections

Before it appears onscreen, a table view asks you to specify the total number of rows and sections. Your data source object provides this information using two methods:

func numberOfSections(in tableView: UITableView) -> Int  // Optional 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

In your implementations of these methods, return the row and section counts as quickly as possible. Doing so might require you to structure your data in a way that makes it easy to retrieve the row and section information. For example, consider using arrays to manage your table’s data. Arrays are good tools for organizing both sections and rows because they match the natural organization of the table view itself.

The example code below shows an implementation of the data source methods that return the number of rows and sections in a multisection table. In this table, each row displays a string, so the implementation stores an array of strings for each section. To manage the sections, the implementation uses an array (called hierarchicalData) of arrays. To get the number of sections, the data source returns the number of items in the hierarchicalData array. To get the number of rows in a specific section, the data source returns the number of items in the respective child array.