有没有Swift的等效实现?
__attribute((objc_requires_super))
如果一个方法不调用其超类方法,它会发出警告吗?
基本上,我想要在覆盖的方法没有调用其超类方法时发出警告(或者更好的是,抛出编译器错误)。
有没有Swift的等效实现?
__attribute((objc_requires_super))
如果一个方法不调用其超类方法,它会发出警告吗?
基本上,我想要在覆盖的方法没有调用其超类方法时发出警告(或者更好的是,抛出编译器错误)。
不,Swift没有相当于__attribute((objc_requires_super))
的等效物。
等效功能Swift Attributes没有此类属性。
Swift继承文档的这一部分如果提到了这样一个特性,它只是说:
当为子类提供方法、属性或下标重写时,有时使用现有的超类实现作为你的重写的一部分会很有用。
请注意,您可以使用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在评论中提到的,如果子类被再次子类化,则会出现问题。
我不断言这种方法是否风格上好,但肯定是可能的。
MoreFancyStarship
是 FancyStarship
的子类,它的 super.tractorBeamDidEnable
方法不再是空方法。 - Bryan ChenAbstractStarship
可以在 enableTractorBeam()
返回之前调用 tractorBeamDidEnable()
的实现时出现运行时错误。当然,这也是一个不完美的解决方案,因为开发人员在代码运行之前没有任何指示表明这是错误的,不像 objc_requires_super
。 - Aaron Brager