Swift-必须由子类覆盖的类方法 [英] Swift - class method which must be overridden by subclass

查看:563
本文介绍了Swift-必须由子类覆盖的类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有在Swift中制作纯虚函数的标准方法。

解决方案,每个子类都必须覆盖该子类,否则子类将导致编译时错误? div>

您有两个选择:



1。使用协议



将超类定义为协议而不是类



Pro >:编译时检查每个子类(不是实际的子类)是否实现了所需的方法



Con :超类(协议)无法实现方法或属性



2。断言方法的超级版本



示例:

  class超类{
func someFunc(){
fatalError(必须重写)
}
}

class子类:超类{
覆盖func someFunc(){
}
}

Pro :可以在超类中实现方法和属性



Con :无需编译时检查


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?

解决方案

You have two options:

1. Use a Protocol

Define the superclass as a Protocol instead of a Class

Pro: Compile time check for if each "subclass" (not an actual subclass) implements the required method(s)

Con: The "superclass" (protocol) cannot implement methods or properties

2. Assert in the super version of the method

Example:

class SuperClass {
    func someFunc() {
        fatalError("Must Override")
    }
}

class Subclass : SuperClass {
    override func someFunc() {
    }
}

Pro: Can implement methods and properties in superclass

Con: No compile time check

这篇关于Swift-必须由子类覆盖的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆