-1

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.

iOS
  • 5,450
  • 5
  • 23
  • 25
  • 2
    I would recommend you to read this: https://medium.com/@stanislavsmida/dont-use-extensions-primary-for-structuring-your-code-7b3af9baae17 – Milan Nosáľ Apr 05 '18 at 06:50
  • you're not overriding anything here, UITableViewDelegate,UITableViewDataSource are protocols , you have conform those, so you need to implement required methods. So remove override keyword from this. – Suryakant Sharma Apr 05 '18 at 07:07
  • @MilanNosáľ The shared link is helpful – iOS Apr 05 '18 at 08:38
  • @Suryakant The implementation has already been done at base class "BaseTableViewController". Trying to understand if we can override the methods inside extension of class "ChildViewController". Please suggest some right approach to achieve the same – iOS Apr 05 '18 at 08:39

1 Answers1

1

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.

Zaphod
  • 6,758
  • 3
  • 40
  • 60
  • The implementation has already been done at base class "BaseTableViewController". Trying to understand if we can override the methods inside extension of class "ChildViewController". Please suggest some right approach to achieve the same. – iOS Apr 05 '18 at 08:37
  • I edited it to suggest the approach that seems to be suitable. – Zaphod Apr 05 '18 at 08:50