Recusiwe Recusiwe - 1 year ago 66
Swift Question

Best way to populate rows in section in UITableView?

I'm building an app, where I got several sections in an UITableView. My current solution is collecting my data in a dictionary, and then pick one key for every section. Is there a better solution?

Answer Source

Here is a quick example that I wrote. Please note, it error-prone since it is not checking wether the keys exists not does it create a proper cell.

You could do this with a dictionary as well, since you can iterate over its content.

Hope it helps:

class AwesomeTable: UITableViewController {

    private var tableContent: [[String]] = [["Section 1, row 1", "Section 1, row 2"], ["Section 2, row 1", "Section 2, row 2"]]

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return tableContent.count

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableContent[section].count

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

        let item = tableContent[indexPath.section][indexPath.row]

        cell.textLabel?.text = item

        return cell

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download