Swift - 必须被子类覆盖的类方法
问题描述:
是否有一种标准方法可以在 Swift 中创建纯虚函数",即.必须被每个子类覆盖,如果不是,会导致编译时错误?
Is there a standard way to make a "pure virtual function" in Swift, ie. one that must be overridden by every subclass, and which, if it is not, causes a compile time error?
答
您有两个选择:
将超类定义为协议而不是类
Define the superclass as a Protocol instead of a Class
Pro:编译时检查每个子类"(不是实际的子类)是否实现了所需的方法
Pro: Compile time check for if each "subclass" (not an actual subclass) implements the required method(s)
Con:超类"(协议)无法实现方法或属性
Con: The "superclass" (protocol) cannot implement methods or properties
示例:
class SuperClass {
func someFunc() {
fatalError("Must Override")
}
}
class Subclass : SuperClass {
override func someFunc() {
}
}
优点:可以在超类中实现方法和属性
Pro: Can implement methods and properties in superclass
缺点:没有编译时检查