【问题标题】:Marking an open method final in subclass在子类中标记 open 方法 final
【发布时间】:2018-03-13 04:16:16
【问题描述】:

考虑以下示例:

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 关键字,则会出现编译器错误提示

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

【问题讨论】:

    标签: ios swift swift4


    【解决方案1】:

    你可以通过像这样创建方法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 的情况下将其公开。

    【讨论】:

    • 酷...只使用public 会引发编译错误,但使用final public 可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 2012-05-14
    • 2020-03-06
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多