Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override non-dynamic class delaration [duplicate]

With new Xcode 8.3, I get the error:

Cannot override a non-dynamic class declaration from an extension

from the line of code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

How I can avoid this warning?

like image 214
UnRewa Avatar asked Mar 29 '17 08:03

UnRewa


People also ask

Can we override method in extension Swift?

If a protocol defines a method, and provides a default implementation in an extension, a class can override that method, and the override will be called for any reference to the instance, even if the reference's type is declared as the protocol.

Can we override method in extension?

Extension methods cannot be overridden the way classes and instance methods are. They are overridden by a slight trick in how the compiler selects which extension method to use by using "closeness" of the method to the caller via namespaces.

What is override func in Swift?

Swift version: 5.6. The override is used when you want to write your own method to replace an existing one in a parent class. It's used commonly when you're working with UIViewControllers , because view controllers already come with lots of methods like viewDidLoad() and viewWillAppear() .


2 Answers

Extensions can add new functionality to a type, but they cannot override existing functionality.

You have two options:

  1. Move your method inside the Class-scope, instead of extension.

  2. Add dynamic type to your method (where it's defined), like example.

Example:

@objc open dynamic func onLog(_ message: String) -> Void {
    print("Info: \(message)");
}
like image 84
jamal zare Avatar answered Oct 13 '22 20:10

jamal zare


which means, you can't not override like super class delegate method in extension. the way you can do is mv extension override method to subclass declare.

final class DEMO, UITableViewDataSource, UITableViewDelegate { 

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
         return sectionHeader
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 40
    }

}
like image 42
looseyi Avatar answered Oct 13 '22 20:10

looseyi