Search code examples
iosuitableviewswift3swift4ios-extensions

UITableViewDelegate and UITableviewDataSource : Cannot override a non-dynamic class declaration from an extension - Swift 4


I am trying to override the UITableViewDelegate methods inside extension.The base class has already implemented the methods. Please find the details below:

   Base Class:

   class BaseTableViewController:UITableViewDelegate,UITableViewDataSource{

      //Base Class. The delegate and datasource methods has been implemented
   }

  class ChildViewController: BaseTableViewController{

     //Inherited class
  }

  extension ChildViewController  { 

      //Trying to override the Tableview Delegate and Datasource methods but getting error.
  }

Error Detail:

enter image description here

I am trying to do the conversion from Swift 3.0 to Swift 4.0. The implementation was working fine with Swift 3.0 but got error in Swift 4.0.

I have looked into below links: Override non-dynamic class delaration

Please suggest the right approach for the above implementation.


Solution

  • The right approach seems to override methods from protocols inside the class and not into an extension:

    class BaseTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            ...
        }
    }
    
    
    class ChildViewController: BaseTableViewController {
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            ...
        }
    }
    

    Extensions are meant to add new functionalities, not override existing ones. Another approach would be to delegate those functions on an external object.