Swift等于__attribute((objc_requires_super))?

有Swift等于吗?
__attribute((objc_requires_super))

如果方法不称为超级方法,则会发出警告?

基本上,如果覆盖的方法不调用其超级方法,我想提醒(甚至更好的是抛出编译器错误)。

不,没有Swift等价于__attribute((objc_requires_super))。

等效功能,Swift Attributes,不包含此类属性。

Swift inheritance documentation的这个功能将被提及的部分只提到:

When you provide a method,property,or subscript override for a subclass,it is sometimes useful to use the existing superclass implementation as part of your override.

请注意,您可以使用final来防止覆盖函数,因此您可以通过提供由不可覆盖的方法调用的空的可覆盖方法来有效地完成所需的任务:

class AbstractStarship {
    var tractorBeamOn = false

    final func enableTractorBeam() {
        tractorBeamOn = true

        println("tractor beam successfully enabled")

        tractorBeamDidEnable()
    }

    func tractorBeamDidEnable() {
        // Empty default implementation
    }
}

class FancyStarship : AbstractStarship {
    var enableDiscoBall = false

    override func tractorBeamDidEnable() {
        super.tractorBeamDidEnable() // this line is irrelevant

        enableDiscoBall = true
    }
}

子类然后将覆盖可覆盖的方法,无论他们是否调用super还是不重要,因为超类的实现是空的。

正如Bryan Chen注释中的注释所示,如果子类被子类化,则会分解。

我没有声称这种做法在风格上是好的,但这当然是可能的。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...