A better, exhaustive switch in UITableView protocols

I have written a lot of not-good-looking code inside UITableViewDelegate and UITableViewDataSource. Here is a very handful trick I’ve figured out a few months ago that has worked like a charm since then.

Fernando Martín Ortiz
iOS App Development

--

The common way

UITableView protocols are often written using expressions like these:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0: // Dequeue a cell for section 0
case 1: // Dequeue a cell for section 1
// And so on...
default: fatalError("Unhandled section \(indexPath.section)")
}
}

I’m probably exaggerating here. I know there are some workarounds, but I bet you aren’t proud of what you are doing in these kind of situations.

The better solution

I prefer creating a protocol extension called ReusableViewEnum with two methods, one for obtaining all cases inside an enum implementing it and a build method that I use to obtaining a case with a section value without receiving an optional value.

Here goes the code:

I hope this will help you as much as me. Thank you!

--

--