Ios 在子类中标记开放式方法final
考虑以下示例:Ios 在子类中标记开放式方法final,ios,swift,swift4,Ios,Swift,Swift4,考虑以下示例: open class A { // This class is from the SDK and cannot be modified in anyway. open func aFunc() {} } 下面是我自己的类,我需要打开该类以供其他人重写。但该方法不应可用于重写 open class B : A { // This has to be open for others to override. override open func aFunc() {}
open class A { // This class is from the SDK and cannot be modified in anyway.
open func aFunc() {}
}
下面是我自己的类,我需要打开该类以供其他人重写。但该方法不应可用于重写
open class B : A { // This has to be open for others to override.
override open func aFunc() {} // I need to make this **final** somehow so the subclasses cannot override this.
}
是否可以在类B
final中标记aFunc()
方法?
我尝试添加final
关键字,但出现了一个编译器错误
实例方法不能同时声明为“final”和“open”
如果我删除open
关键字,则会出现一个编译器错误
重写实例方法必须与它的声明一样可访问
覆盖
您可以通过如下方式公开方法
:
open class A { // This class is from the SDK and cannot be modified in anyway.
open func aFunc() {}
}
open class B : A { // This has to be open for others to override.
override final public func aFunc() {}
}
open
关键字用于让来自不同模块的子类重写,而public
关键字只允许访问不同的模块,不允许重写。如果您只想在您的模块中覆盖此方法,而不想在其他模块中覆盖此方法,您可以在不使用final
的情况下将其公开,您可以通过如下方式将此方法公开:
open class A { // This class is from the SDK and cannot be modified in anyway.
open func aFunc() {}
}
open class B : A { // This has to be open for others to override.
override final public func aFunc() {}
}
open
关键字用于让来自不同模块的子类重写,而public
关键字只允许访问不同的模块,不允许重写。如果您只想在您的模块中覆盖此方法,而不想在其他模块中覆盖此方法,您可以在不使用final
的情况下将其公开。。。使方法只公开
会引发编译错误,但使它们最终公开
效果很好。酷。。。使方法只public
会抛出编译错误,但使它们final public
工作正常。