[swift-evolution] Add code to super methods.

Joe Groff jgroff at apple.com
Tue Nov 29 14:28:52 CST 2016


> On Nov 28, 2016, at 7:22 PM, Dave Abrahams via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
> on Thu Nov 24 2016, Michael Ilseman <swift-evolution at swift.org> wrote:
> 
>>> On Nov 17, 2016, at 2:54 AM, Tino Heth via swift-evolution
>> <swift-evolution at swift.org> wrote:
>>> 
>>> An equivalent of "NS_REQUIRES_SUPER" (hopefully with a better name ;-) has been requested several
>> times, but never got the momentum it deserves.
>>> Considering the current confusion (especially in UIKit), it would be
>>> really nice to have some help from the compiler, and I wonder how
>>> composition and protocols would be helpful here at all.
>>> 
>> 
>> As an intermediary measure, this seems like an interesting QoI
>> improvement for the compiler: warn when super.foo() is not called in
>> the overridden method. 
> 
> Please no.  Methods that need to be called when they are overridden are
> almost always a result of poor design.
> 
>    “I don't always do Object Oriented Programming, but when I do, I use
>    the Template Method Pattern"
> 
> understating-the-case-ly y'rs,

If you must enforce that a subclass override calls its super implementation, you could enforce this via the type system, by creating a token type that only the super implementation is able to construct:

open class Base {
  public struct SuperFoo {
    // Only the super implementation can create SuperFoos.
    fileprivate init() {}
  }

  open func foo() -> SuperFoo {
    doBaseStuff()
    return SuperFoo()
  }
}

// In another file...

class Derived: Base {
  override func foo() -> SuperFoo {
    // Must call super to get a SuperFoo that lets us out of the function
    let result = super.foo()
    doDerivedStuff()
    return result
  }
}

-Joe


More information about the swift-evolution mailing list