Swift 相当于 __attribute((objc_requires_super))? [英] Swift equivalent to __attribute((objc_requires_super))?

查看:27
本文介绍了Swift 相当于 __attribute((objc_requires_super))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 Swift 等价于

Is there a Swift equivalent to

__attribute((objc_requires_super))

如果一个方法没有调用它的超级方法,它会发出警告?

which gives a warning if a method doesn't call it's super method?

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

Basically, I want to warn (or even better, throw a compiler error) if an overridden method doesn't call its super method.

推荐答案

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

No, there is no Swift equivalent to __attribute((objc_requires_super)).

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

The equivalent feature, Swift Attributes, contains no such attribute.

Swift 继承文档提到这样的功能只说:

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

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 防止覆盖函数,因此您可以有效通过提供被调用的空的可覆盖方法来实现您想要的通过不可覆盖的方法:


Note that you can prevent overriding functions using final, so you could effectively accomplish what you want by providing empty overridable methods that are called by non-overridable methods:

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 无关紧要,因为超类的实现是空的.

Subclasses would then override the overridable methods, and it wouldn't matter whether they called super or not since the superclass's implementation is empty.

正如 Bryan Chen 在评论中指出的那样,如果子类被子类化,这会失效.

As Bryan Chen notes in the comments, this breaks down if the subclass is subclassed.

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

I make no claims to whether this approach is stylistically good, but it is certainly possible.

这篇关于Swift 相当于 __attribute((objc_requires_super))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆