使用扩展扩展多个 类

Use an extension to extend multiple classes

我正在使用如下所示的表视图数据源扩展。我想将此扩展应用于我的应用程序中的多个 tableview 控制器。我看不出有任何简单的方法可以允许单个通用扩展扩展多个 类 而无需将相同的代码复制并粘贴到不同的单独扩展中。可能的解决方案是改为定义 ,然后扩展协议。然而在那些情况下,它们在协议中定义然后扩展的函数是 自定义函数 而在表视图数据源扩展中我想应用于许多 类,函数是 覆盖 标准表视图数据源方法的功能。我可以使用此模式通过此代码扩展多个 类 还是有其他解决方案。

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
    }
}

您可以创建 UITableViewController 的子类,将扩展添加到您的子类,然后让您想要的所有其他 table 视图控制器继承您创建的子类。