简体   繁体   English

在swift中使用final作为子类

[英]Using final for subclass in swift

I have two class A , B. B is the subclass of A. Can I use final for class B. I want to reduce the dynamic dispatch. 我有两个A类,B。B是A的子类。我可以使用final作为B类。我想减少动态调度。 What if there is method in class b that is overriding the class A method . 如果b类中的方法覆盖了A类方法,该怎么办? How method dispatching will work? 方法调度如何工作?

class A {
     ///
}

final class B : Class A {

}

Yes, You can 是的你可以

Swift gives us a final keyword just for this purpose: when you declare a class as being final, no other class can inherit from it. Swift为此提供了一个final关键字:当你将一个类声明为final时,没有其他类可以继承它。 This means they can't override your methods in order to change your behavior – they need to use your class the way it was written. 这意味着他们无法覆盖您的方法以改变您的行为 - 他们需要按照编写的方式使用您的类。

The final keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. final关键字是对类,方法或属性的限制,表示无法覆盖声明。 This allows the compiler to safely elide dynamic dispatch indirection. 这允许编译器安全地忽略动态调度间接。

So you can use it. 所以你可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM