UITableViewDelegate and DataSource implementations in protocol extension

There is a bunch in my application UITableView

that essentially does the same thing, so I created a protocol called Presenter

and made them all match it. For simplicity, I have decided to implement the methods UITableViewDelegate

and UITableViewDataSource

extensions of this protocol. However, I came across several errors and warnings as shown below: enter image description here

Adding @objc

to the protocol didn't help.

Now I know it UITableView

might be easier to subclass , but I was wondering if there is a painless solution to this problem. Since someone is just familiar with Swift

, I am trying to implement the protocols as best 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
    }
}

      

+3


source to share





All Articles