在Swift 4中,无法覆盖扩展声明

PGD*_*Dev 13 extension-methods ios swift swift4

我最近将我的代码迁移到了Swift 4.我面临扩展问题,即

来自扩展的声明无法覆盖

我已经阅读了多个重新发布此问题的帖子.但他们都没有接受下面描述的情景:

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...
    }
}
Run Code Online (Sandbox Code Playgroud)

根据Apple的说法,

扩展可以为类型添加新功能,但它们不能覆盖现有功能.

但在上面的场景中,我没有覆盖isValid()扩展中的方法.它在SampleCell类定义本身中被重写.不过,它正在给出错误.

Tam*_*gel 10

但在上面的场景中,我没有覆盖isValid()扩展中的方法.

isValid扩展中声明.

错误几乎说如果一个函数以这种方式声明,它就不能被覆盖.

该声明对扩展扩展都有效.

  • 其背后的原因是什么?为什么不允许这样做? (2认同)

Ada*_*ble 6

只要您@objc使用协议,就可以覆盖扩展名中的声明。在Swift 4.2中:

class BaseClass {}
class SubclassOfBaseClass: BaseClass {}

@objc protocol IsValidable {
    func isValid() -> Bool
}

extension BaseClass: IsValidable {
    func isValid() -> Bool { return false }
}

extension SubclassOfBaseClass {
    override func isValid() -> Bool { return !super.isValid() }
}

BaseClass().isValid()           // -> false
SubclassOfBaseClass().isValid() // -> true
Run Code Online (Sandbox Code Playgroud)


Pun*_*rma 5

在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
Run Code Online (Sandbox Code Playgroud)