Search code examples
swiftxcode6xcode6.1

Swift: Cannot Override with a stored property and 'required' initializer 'init(coder:)' must be provided by subclass for 'UIViewController'


I have the code below:

import UIKit

class tabBarVC: UIViewController, UITabBarControllerDelegate {

    var tabBarController : UITabBarController // ERROR1:  Cannot override with a stored property 'tabBarController'

    override init() {
        super.init()
        self.tabBarController = UITabBarController()

    }
    override func viewDidLoad() { //ERROR2:  'required' initializer 'init(coder:)' must be provided by subclass for 'UIViewController' 
        super.viewDidLoad()
    }
}

I need to define and initialize a variable called tabBarController that can be accessed as self.tabBarController.

I'm getting two errors by Xcode:

  1. Cannot override with a stored property tabBarController
  2. 'required' initializer init(coder:) must be provided by subclass for UIViewController

What am I doing wrong?

**EDIT **

import UIKit

class tabBarVC: UIViewController, UITabBarControllerDelegate {

    var tabBarController : UITabBarController() // Error: "Consecutive declarations on a line must be separated by ';'"

    override init() {
        super.init()
        self.tabBarController?.delegate = self
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Solution

  • Since you are not assigning anything specific to tabBarController, you can just do:

     var tabBarController = UITabBarController()
    

    and not mention it in the init method.

    For error 2 you just need to follow what it says and add init(coder:) because you are subclassing that class without a designated initializer.