作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在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/
我是一名优秀的程序员,十分优秀!