UITableView with switchable Datasources
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:


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.
