0

I've got a superclass UIViewController class that implements a couple of default methods, e.g.:

class Super: UIViewController {
    override func viewDidLoad () {
        setupView()
    }

    func setupView () {
        initToolbar()
        setPageTitle()
    }

    func initToolbar () {
         // some code..
    }

    func setPageTitle () {
         // nothing?
    }
}

and subclasses that inherit from Super:

class Sub: Super {
    override func setPageTitle () {
        self.title = "custom title"
    }
}

I'd like to force all subclasses to override the setPageTitle() method (forcing a compile time error if no implementation is present). However, the only way I've managed to achieve this is providing a default implementation in the Super class that contains an assert statement, causing the app to crash if it has not been overriden. This is not really what I was after as the error is only present at runtime and ideally i'd like a compile time warning/error if the method has no implementation. Is there any way to set this method to be overriden as a requirement? Similar to abstract methods in other languages?

I thought about using protocols & extensions but it looks like with extensions I can't override the viewDidLoad method and this is necessary for the superclass.

Any ideas?

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Probably a duplicate of https://stackoverflow.com/questions/24110362/abstract-functions-in-swift-language – rmaddy Oct 25 '17 at 17:43
  • The only way that comes to my mind is the one with assert, so I guess you're stuck with that.. – Milan Nosáľ Oct 25 '17 at 18:02
  • You can create a protocol which declares the required methods. Every view controller which should implement these methods has to derive from this protocol, too. – clemens Oct 25 '17 at 18:12

0 Answers0