Swift override protocol methods in subclasses

I have a base class that implements an extension that conforms to the protocol as shown below:

protocol OptionsDelegate { func handleSortAndFilter(opt: Options) } extension BaseViewController: OptionsDelegate { func handleSortAndFilter(opt: Options) { print("Base class implementation") } } 

I have a subclass of "InspirationsViewController" that inherits from BaseViewController. And I redefine the protocol method in the extension, as shown below:

 extension InspirationsViewController { override func handleSortAndFilter(opt: Options) { print("Inside inspirations") } } 

I get an error when I redefine the function "handleSortAndFilter" in a subclass extension: "Decryption in extensions cannot yet override"

But I do not see a similar problem when I implemented the UITableView and delegation data methods.

How to avoid this error?

+7
source share
2 answers

Use the protocol extension with the where clause. He works.

 class BaseViewController: UIViewController { } extension OptionsDelegate where Self: BaseViewController { func handleSortAndFilter(opt: Options) { print("Base class implementation") } } extension BaseViewController: OptionsDelegate { } class InsipartionsViewController: BaseViewController { } extension OptionsDelegate where Self: InsipartionsViewController { func handleSortAndFilter(opt: Options) { print("Inspirations class implementation") } } 
+9
source

As far as I know, you cannot override methods in extensions. Extensions can only perform the following actions: "Extensions in Swift can:

  • Add properties of computed instances and properties of computed type
  • Define instance methods and type methods
  • Provide new initializers
  • Define Indexes
  • Define and use new nested types
  • Make existing type conform to protocol

Excerpt from: Apple Inc. "Fast programming language (Swift 3.0.1)."

-one
source

Source: https://habr.com/ru/post/1013545/


All Articles