如何在Swift中强制实现子类继承的重写?

3

我在 Swift 中有以下层次继承关系:

class Base {

    func method1() { }
    func method2() { }
}

class Child: Base {

    override func method1() { }
    func method3() { }
}

class GrandChild: Child {

}

现在,我想强制GrandChild重写来自Base类的method1()和来自Child类的method3()。如何做到这一点?是否有任何解决方法或更好的方法?

@LalKrishna,那并没有回答我的问题。我的意图不仅仅是使类成为抽象的,而是在base->child->grandchild流中传播限制。 - Sazzad Hissain Khan
Swift 目前不支持此功能。 - Rohan Bhale
1
由于 Swift 没有抽象类,因此甚至无法强制子类覆盖方法。 如果不知道使用情况,很难建议解决方案,但在 Swift 中的一般建议是使用协议。 - Joakim Danielson
1个回答

2

在Swift中,无法在编译时执行此操作。Swift没有强制实施方法覆盖的特性。

但是有一个解决方法。

您可以通过放置致命错误fatalError("Must Override")来实现。

考虑以下示例。

class Base {
    func method1() {
      fatalError("Must Override")
    }
    func method2() { }
}

class Child: Base {
    override func method1() { }
    func method3() {
      fatalError("Must Override")
    }
}

class GrandChild: Child {
   func method1() { }
   func method3() { }
}

但是上述方法不会产生任何编译时错误。为此,有另一种解决方法。
你可以创建一个协议。
protocol ViewControllerProtocol {
   func method1()
   func method3()
}

typealias ViewController = UIViewController & ViewControllerProtocol

如果您实现了此协议但未实现方法,则编译器将生成错误。

作为Swift中协议的一个特性,您还可以在协议扩展中提供方法的默认实现。

希望这能帮到您。


1
值得一提的是,这将在运行时被检测到。 - Sazzad Hissain Khan
@nishith Singh 协议方法不会强制GrandChild。 - Rohan Bhale
是的,@RohanBhale,你说得对。这是这种方法中的一个限制。 - nishith Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接