Chris Hannah
My little piece of the internet

Currently Listening

A Simple and Clean Way to Store Sectioned Data for a UITableView

This is just something small in Swift/iOS that I find pretty handy, so I thought I’d share it just in case it can help.

So, the problem is that creating data that has to be presented in a UITableView can be somewhat complex, especially if you have multiple columns. This solution is geared towards quickly creating dummy data, but I think it could be expanded into an overall DataSource solution.

Anyway, we’ll start with the current way of managing sections. Usually, you would have some kind of enum that would correspond to a section integer, and also however many arrays of data for the number of sections. You would then either use the section enum to find the correct array. Or maybe you’d use a 2d array, and then use it as the index.

It just doesn’t see very Swift to me. In Swift, everything is simple, easy to read, and is pretty easy to write. So I thought I’d come up with a slight abstraction.

My first idea was to just make two structs, one for a Section, and another for a Table:

struct Section {
    var title: String
    var items: [String]
}

struct Table { var sections: [Section] }

You could then go ahead, create individual sections, and add them to one table. Easy.

Example Data

Animals:

  • Cats
    • Tiger
    • Lion
    • Lynx
  • Bears
    • Grizzly
    • Black
    • Polar

Example Code

let catSection = Section(title: "Cats", items: ["Tiger", "Lion", "Lynx"])
let bearSection = Section(title: "Bears", items: ["Grizzly", "Black", "Polar"])

let animalTable = Table(sections: [catSection, bearSection])

I just find that a bit more readable.

It also makes the number of sections and rows a bit simpler:

let numberOfSections = animalTable.sections.count
let numberOfRows = animalTable.sections[0].items.count

However, you can add this functionality to the Table struct Which makes it much, much better.

Here is the definition of the ComplexTable struct:

struct ComplexTable {
    var sections: [Section]

func numberOfRows(forSection section: Int) -> Int { if sections.count > section { return sections[section].items.count } else { return 0 } }

func numberOfSections() -> Int { return sections.count } }

Which would make it this easy to get the row and section counts:

let numberOfSections = complexAnimalTable.numberOfSections()
let numberOfRows = complexAnimalTable.numberOfRows(forSection: 0)

So there you go.

It’s nothing big, and it won’t win many programming awards. But it’s a small piece of code that will certainly help me when I’m just messing around with tables, or I want a really clean and simple way to store small amounts of organised data.

Reply via Email