2 Replies
      Latest reply on May 2, 2016 4:25 AM by eskimo
      zespri Level 1 Level 1 (0 points)

        My project has a:

        class BaseViewController: UIViewController


        and a:

        class PlayerViewController: BaseViewController


        I want to add:

            init(player playerObject: Player)


        to PlayerViewController.  According to my googling, and experimenting, I seem to need to have the following in place.


        class BaseViewController: UIViewController {
            required init?(coder aDecoder: NSCoder) {
                super.init(coder: aDecoder)
            override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
                super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)




        class PlayerViewController: BaseViewController {
            let player: Player!
            init(player playerObject: Player)
                self.player = playerObject
                super.init(nibName: nil, bundle: nil)
            required init?(coder aDecoder: NSCoder) {
                fatalError("init(coder:) has not been implemented")


        Does this make sense? (It just seemed like a lot of 'extra' code)  The code that most feels superflous is the init(coder:) initializer in PlayerViewController.

        However if I comment it out, I get the compile error: 

        'required' initializer 'init(coder:)' must be provided by subclass of 'BaseViewController'


        I guess I don't see why it's needed when it's not called by the init(playerObject:) initializer I want to add. 

        any insite would be appreciated.

        • Re: swift what init code to I need to write to add a custom init function in a class that derives from a subclass of UIViewController
          QuinceyMorris Level 8 Level 8 (6,060 points)

          First, I don't know why the SDK makes 'init?(coder:)' required — presumably there's a good reason, which means you just have to live with it.


          Second, you shouldn't need to implement either 'init' in BaseViewController, if all you're doing is calling super. According to the Swift rules, if BaseViewController doesn't declare any designated initializers, it inherits all of them from its superclass (UIViewController).


          Third, by the same rule, your custom 'init' in PlayerViewController prevents inheritance of designated controllers from its ancestor classes. This is what you want for 'init(nibName:bundle")', because you don't want that to be available for PlayerViewController. It's also what you apparently want for 'init?(coder:)', but unfortunately there's that 'required' … um … requirement. See above under "live with it". Think of it as a legacy from the bad old Objective-C days.