gpt4 book ai didi

ios - 如何在 Swift 中强制覆盖孙子类?

转载 作者:行者123 更新时间:2023-12-01 22:00:34 26 4
gpt4 key购买 nike

我在Swift中有以下层级继承关系,

class Base {

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

class Child: Base {

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

class GrandChild: Child {

}

现在,我想强制 GrandChild 覆盖Base 类和 中的method1()来自 Child 类的 method3()我该怎么做?任何解决方法或更好的方法?

最佳答案

在 Swift 中无法在编译时完成。 Swift 中不存在强制方法覆盖的功能。

但有一个变通办法。

您可以通过放置 fatal error 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)。

protocol ViewControllerProtocol {
func method1()
func method3()
}

typealias ViewController = UIViewController & ViewControllerProtocol

因此,如果您实现此协议(protocol)而不实现方法,编译器将生成错误。

作为 Swift 协议(protocol)的一项功能,您还可以在协议(protocol)扩展中提供方法的默认实现。

希望这对您有所帮助。

关于ios - 如何在 Swift 中强制覆盖孙子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60144511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com