UITableViewDelegate and DataSource implementations in a protocol extension

Viewed 261

I have a bunch of UITableViews in my app that essentially do the same thing, so I created a protocol called Presenter and made them all conform to it. For simplicity I decided to implement UITableViewDelegate and UITableViewDataSource methods within extensions of said protocol. However, I stumbled upon multiple errors and warnings as shown below: enter image description here

Adding @objc to the protocol did not help.

Now I know that making a subclass of UITableView may be easier, but I was wondering if there is a painless solution to this problem. As someone just getting acquainted with Swift, I'm trying to implement protocols as much as I can.

Here's the code:

protocol Presenter {
    var viewer: Viewer { get }
}

extension Presenter where Self: UITableViewDelegate {
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return viewer.header
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewer.height
    }
}

extension Presenter where Self: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewer.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: GenericCell.identifier, for: indexPath) as! GenericCell
        cell.content = viewer.viewable(at: indexPath.row)
        return cell
    }
}
0 Answers
Related