UITableView with switchable Datasources

Abhishek Bedi
Jul 22, 2017 · 2 min read

UITableview is the most common iOS UI Element that we reach out to when we want to display a list of items. And usually, we end up writing repeated code for displaying a different set of data for a similar requirement.

Here in this post, I will try to use the same UITableView with different datasources in an Xcode Playground.


This article is inspired by Ritesh Gupta’s article on Extend Swift Associated Types in Protocol to compose behaviour!


Final Outcome:

TableView with Sports Persons List
TableView with Movie Stars list

Step 1 : Setting up a UITableView in an Xcode Playground.

To setup a UITableView in a playground is pretty straight forward. The below gist is self explanatory.

Step 2: Creating different datasources

Since we want to switch between UITableView’s datasources, we need to create different datasources. Here I am creating two datasources —

  • SportsDatasource (will have data of type SportPerson)
  • MovieStarsDatasource (will have data of type MovieStar)

Both the above datasources will conform to one common protocol — Data Provider.

SportsDatasource and MovieStarsDatasource will have their own UITableViewDataSource methods to customize the UI and the ViewController can now easily switch between datasources.

Here for the purpose of understanding , SportsDatasource and MovieStarsDatasource to work in a similar fashion i.e. simply display data with title. This is just a simple demonstration and not a full fledged solution.

Hope you like this article. Feel free to comment below.

Abhishek Bedi

Written by

The Power Of Imagination 🤔 … You Can’t Even Imagine 😇

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade