Swift equivalent to __attribute((objc_requires_super))?

swift

Solution

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

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

The section of the Swift inheritance documentation where such a feature would be mentioned says only:

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.

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
    }
}

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.

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.

Problem

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.

Original source