I am using a tableview datasource extension as shown below. I want to apply this extension to multiple tableview controllers in my app. I can't see any simple way to allow a single generic extension to extend multiple classes without copy & pasting the same code into different individual extensions. Possible solution is to define a protocol instead and then extend the protocol. in those cases however the functions they are defining in the protocol and then extending are custom functions whereas in the tableview datasource extension I want to apply to numerous classes, the functions are override functions of the standard tableview datasource methods. Can I use this pattern to extend multiple classes with this code or is there some other solution.
extension PopularTableViewController
{
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return fetchedResultsController?.sections?.count ?? 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections = fetchedResultsController?.sections, sections.count > 0 {
return sections[section].numberOfObjects
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let sections = fetchedResultsController?.sections, sections.count > 0 {
return sections[section].name
} else {
return nil
}
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return fetchedResultsController?.sectionIndexTitles
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return fetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
}
}
You can make a subclass of UITableViewController, add the extension to your subclass, then have every other table view controller you want inherit from the subclass you made.