Blog

Functional Snippet #21: Typed Table View Controllers

This weeks snippet deals with the bread and butter of iOS development: table view controllers. As a first step, we create a subclass of UITableViewController, but with an added generic parameter:

class MyTableViewController<A>: UITableViewController {

Now, we can add a property that stores the items as an array, and when a new value is set, the table view gets reloaded:

    var items: [A] = [] {
        didSet { self.tableView.reloadData() }
    }

We’ll also have a configure cell function that, given a cell and an item, configures the cell:

    var configureCell: (UITableViewCell, A) -> () = { _ in () }

Finally, we override an initializer (we need to do this because of making a generic subclass), and have a very simple implementation of cellForRowAtIndexPath and numberOfRowsInSection:

    override init(style: UITableViewStyle) {
        super.init(style: style)
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
        configureCell(cell, items[indexPath.row])
        return cell
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
}

That’s all there is to it. Now we can present a list of A items in a table view, while being sure that our configureCell function gets passed an element of the right type.

Update: the code above doesn’t work at runtime, unfortunately. See the next snippet for a working version.

Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts