Abstract class in Swift?

I totally agree all of those features are very needed and welcome additions that I believe swift will have in the future. However, I'm still having a hard time to understand how those features would solve the following:

protocol Section {
    associatedtype Item
    var items: [Item] { get }
}

abstract class TableViewController<S: Section>: UIViewController, UITableViewDataSource {
    let tableView = UITableView()
    let sections: [S]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        self.tableView(tableView, cellForItem: sections[indexPath.section].items[indexPath.row], at: indexPath)
    }


    abstract func tableView(_ tableView: UITableView, cellForItem item: S.Item, at indexPath: IndexPath) -> UITableViewCell

    abstract func registerCells() {}
}

class DerivedTableViewController: TableViewController<ConcreteSection> {
    // It would be awesome if the compiler told me that I forgot implementing
    // the abstract methods
}

This would avoid a lot of fatalErrors or abstractMethod Never returning methods that will explode only at runtime.

Could you show me how you would use the features you mentioned to solve this kind of problem? Maybe I already can employ some of your ideas right now and improve my code base.

3 Likes