1

Right now, I achieve this by doing the following:

class Base {
    func requiredMethod() { NSException(...).raise() }
}
class Sub: Base {
    override func requiredMethod() { ... }
}

Can I get some help from the compiler here? I don't want to make A a protocol because then I can't provide functionality to my child classes from my parent class.

What I really want is a Scala trait or Java abstract class, but I'm guessing that's not possible in Swift?

joslinm
  • 7,845
  • 6
  • 49
  • 72
  • 1
    AFAIK, that's not possible. You can have required initializers but not methods. Closest you can get is to have fatalError() in your base class method implementation so that it "forces" subclasses to override it, but that's ugly. Also you might look at default protocol implementation in Swift 2. – 0x416e746f6e Jul 08 '15 at 16:38
  • In other words an [abstract class](http://stackoverflow.com/q/24110396/620197)? – Mike D Jul 08 '15 at 16:50
  • Yes, like an abstract class provides but was wondering if work-arounds existed I wasn't aware of. Not simply "yes" / "no". Thanks @Anton, guess it's not possible – joslinm Jul 08 '15 at 16:56
  • What you can do is to define the abstract methods in a protocol, and the shared behavior in a super class. Then inherit the new class from the superclass, and implement the protocol. – Antonio Jul 08 '15 at 16:57
  • with swift 2.0 you can make protocol extensions, providing default functionality to implementing classes – Mario Zannone Jul 08 '15 at 17:09
  • can you show an example @MarioZannone if this gets re-opened? – joslinm Jul 08 '15 at 17:57
  • as suggested in the linked question, have a look at this [WWDC video](https://developer.apple.com/videos/wwdc/2015/?id=408) – Mario Zannone Jul 08 '15 at 18:10

0 Answers0