Swift - 必须被子类覆盖的类方法 [英] Swift - class method which must be overridden by subclass
本文介绍了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
缺点:没有编译时检查
这篇关于Swift - 必须被子类覆盖的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文