Enum and multi section tableView

We need to create multi section tableview quite often. Using Enum make it easier.

Enum has Associated Value that can contain an arbitrary type object. Declare enum case as section and type of associated value is the model that you want to show each section. Now, the type Item can contain the different type object. [Item] is the array contain both Item1 and Item2. All that is left is create UITableViewCell based on model Item1 or Item2 in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath).

enum Item {
   case section1Item(Item1)
   case section2Item(Item2)
class TableView: UITableViewController {
    let items = [Item]()

    override func numberOfSections(in tableView: UITableView) -> Int {
        return items.count

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = items[indexPath.row]
        switch item {
        case .section1Item(let item1):
            return // create item1 cell
        case .section2Item(let item2):
            return // create item2 cell

  • このエントリーをはてなブックマークに追加