【问题标题】:Swift equivalent to __attribute((objc_requires_super))?Swift 相当于 __attribute((objc_requires_super))?
【发布时间】:2020-09-11 09:28:54
【问题描述】:

是否有 Swift 等价于

__attribute((objc_requires_super))

如果方法不调用它的超级方法,它会给出警告?

基本上,如果被覆盖的方法没有调用它的超级方法,我想发出警告(或者更好的是,抛出编译器错误)。

【问题讨论】:

标签: swift


【解决方案1】:

不,没有与__attribute((objc_requires_super)) 等效的 Swift。

等效特征Swift Attributes 不包含此类属性。

Swift inheritance documentation提及此类功能的部分仅说明:

当您为子类提供方法、属性或下标覆盖时,有时将现有的超类实现用作覆盖的一部分很有用。


请注意,您可以防止使用 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 在 cmets 中指出的那样,如果子类被子类化,这就会崩溃。

我不声称这种方法是否风格上很好,但它肯定是可能的。

【讨论】:

  • MoreFancyStarshipFancyStarship 的子类怎么样?它的super.tractorBeamDidEnable 不再是空方法
  • @BryanChen 是的,就冗长和您提到的原因而言,它肯定不是一个完美的替代品。如果你想强制执行它,如果在 enableTractorBeam() 返回之前没有调用 tractorBeamDidEnable() 的实现,AbstractStarship 可能会出现一些运行时错误。当然,这也是一个不完美的解决方案,因为开发人员在代码运行之前没有任何迹象表明这是错误的,这与objc_requires_super 不同。
猜你喜欢
  • 2017-08-08
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多