Ads from extensions cannot be overridden in Swift 4

I recently migrated my code to Swift 4 . There is a problem that I am facing extension , i.e.

Ads from extensions cannot be overridden

I already read some posts fixing this problem. But none of them describes the scenario described below:

class BaseCell: UITableViewCell
{
    //Some code here...
}

extension BaseCell
{
    func isValid() -> String?
    {
        //Some code here...
    }
}

class SampleCell: BaseCell
{
    //Some code here...

    override func isValid() -> String? //ERROR..!!!
    {
        //Some code here...
    }
}

According to Apple

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

But in the above scenario, I am not redefining the method isValid()in the extension. It is redefined in the class definition itself SampleCell. However, it gives an error.

Can anyone give a little more clarity on this topic? Any help is much appreciated.

+4
5

isValid() .

isValid .

, ​​ , .

Edit:

, .

+2

, .

override func isValid() -> String?, ​​ extension BaseCell, BaseCell.

, -, .

, .

+3

Swift 3 , , Objective-C (http://blog.flaviocaetano.com/post/this-is-how-to-override-extension-methods/), , Swift 4. - :

protocol Validity {
    func isValid() -> String?
}

class BaseCell: UITableViewCell, Validity {

}

extension Validity
{
    func isValid() -> String? {
        return "false"
    }
}

class SampleCell: BaseCell {

    func isValid() -> String? {
        return "true"
    }
}


let base = BaseCell()
base.isValid() // prints false

let sample = SampleCell()
sample.isValid() // prints true
+2

Swift , Objective-C. , ( ), @objc func myMethod() Swift.

0

Swift 3, , , , , Swift 4 , . , .

, Swift 4 Objective-C. Swift 3, NSObject, Objective-C . Swift .

, Swift 4 , @objc, Objective-C, Swift: .

Armed with this knowledge, the solution to your problem is to mark the functions in the extension that you want to override as @objc, and then override this function in the child classes, but remember to include the tag @objcso your code will be called at runtime.

WARNING Here's a little work: if you forget to include @objcin override, the compiler will not complain, but your code will not have a dynamic search, so it will never be called at runtime.

So your code should look something like this:

class BaseCell: UITableViewCell {
    //Some code here...
}

extension BaseCell {
    @objc func isValid() -> String? {
        //Some code here...
    }
}

class SampleCell: BaseCell {
    //Some code here...

    @obcj override func isValid() -> String? {
        //Some code here...
    }
}
0
source

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


All Articles