在子类中标记open方法final

时间:2018-03-13 04:16:16

标签: 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() {} // I need to make this **final** somehow so the subclasses cannot override this.
}

是否可以在aFunc()课程中标记B方法?

我尝试添加final关键字,但是编译错误说

  

实例方法不能同时声明'final'和'open'

如果删除open关键字,则会出现编译错误

  

重写实例方法必须与声明一样可访问   覆盖

1 个答案:

答案 0 :(得分:4)

您可以通过制作方法public来实现此目的:

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的情况下将其公开。