Configuring multiple cells with generics in Swift

iOS Developers spend most of their development time dealing with UITableView and UICollectionView. It’s quite straightforward when you need to display a list with the same data type, e.g., list of users. But what if you need to present a bunch of different cells in one table view? That can lead to a real mess!

Let’s imagine the following case. We need to display a feed with a different type of cells; it can be UserCell, CommentCell, ImageCell, etc.

The most obvious solution is to make if statements in method tableView(_:cellForRowAt:) and it can look as follows.

ViewModel:

This code has several issues:

  • If statements. It can become huge and not readable as number of cells grows.
  • Type casting ( as! ). Casts are a code smell.
  • For each data type we can have only one cell.
  • Boilerplate code.

Let’s make this code simpler, clearer and more elegant.

Advantages:

  • No if statements.
  • No typecasting.
  • No boilerplate code.
  • You don’t need to change the code as number of cells grows.
  • Reusable code.

But how to achieve this result? It’s when generic programming comes into play!

Let’s do i<T> with generics

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
Apple Documentation

Generic programming is an excellent way to avoid boilerplate code and helps to define errors during compilation time.

Let’s make a first protocol that each cell should conform to.

Now we can create a generic cell configurator that will configure our table cells.

CellConfigurator - we need this protocol as we can’s hold generic classes in array without defining data types.

TableCellConfigurator - generic class with type constraints for CellType and DataType. Cell can be configured only if DataType of ConfigurableCell equals to DataType used in TableCellConfigurator.

Few adjustments should be made in our ViewModel.

That’s it!

You can add new cells easily without a need to edit your ViewController’s code.

Let’s add a WarningCell to our table view.

  1. Conform to ConfigurableCell protocol.
  2. Add TableCellConfigurator for that cell in ViewModel’s class.

I hope this solution will help you in your projects.

Example project is available on GitHub.

Thanks for reading.

Like what you read? Give Igor Nemenonok a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.