Structuring UITableViews by Using Enums


UITableViews are obviously one of the most used user interface elements on iOS. However, if you are dealing with UITableViews, that have a lot of different sections, your code can become messy quickly. Even worse, it will become very difficult to change the implementation of the UITableView later on. But you can structure UITableViews by using enums.

Hint: This post is using Swift 3, Xcode 8 and iOS 10

So imagine we have an UITableView that has three different kinds of sections. Each section also has another type of table view cell.

I like to create a separate class for the data source of the table view because otherwise the view controller tends to become massive. You can learn more about this topic in the following post: Outsource your UITableViewDataSource!. So, without using enums, a typical data source would look like this:

But what happens if we want to exchange section one and section three? We had to change the code at several positions, at least in the following methods:

  • func numberOfSections(in tableView: UITableView) -> Int
  • func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
  • func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
  • func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

And this is just a small example app. In a real app there are even more methods that we need to change. And if we want to decide the order of the sections at runtime, it would become very tricky. So this approach is a bad one.

Instead, let us define an enum for the section types:

Then we can define the sections in a property:

Now we can decide dynamically what happens in the datasource and delegate methods:

If we now want to change the order of the sections, we just have to adjust the sections array. And that’s just ONE place in the code – compared to four places in our previous example.

Even more, it would be very easy to construct the  sections property at runtime.

Here’s how the whole data source object looks like:

Do you like this approach? Please comment down below!


Image: @ Erce /


Comments are closed