Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required initializers for a subclass of UIViewController

I've been attempting to follow a tutorial about creating a container view controller. It's in Objective-C. I want to convert it to Swift. I've found some of the same questions here, but I didn't get too much out of them.

Here's the code.

import UIKit

class ContainerViewController: UIViewController { // Class "ContainerViewController" has no initializers - That I know why.

    // 'required' initializer 'init(coder:)' must be provided by a subclass of UIViewController

    var currentDetailViewController: UIViewController

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

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

}

I've tried doing what both errors say, but still doesn't work.

like image 808
Jeffrey Avatar asked Nov 10 '14 07:11

Jeffrey


1 Answers

The problem is: If you declare any stored properties without initial value, you must implement your own initializer to initialize them. see this document.

Like this:

var currentDetailViewController: UIViewController

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    currentDetailViewController = UIViewController()
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

convenience override init() {
    self.init(nibName: nil, bundle: nil)
}

required init(coder aDecoder: NSCoder) {
    currentDetailViewController = UIViewController()
    super.init(coder:aDecoder)
}

But, I think this is not what you want.

The correct solution depends on where you initialize currentDetailViewController.

If you always initialize it within viewDidLoad, then you can declare it as an "Implicitly Unwrapped Optional"

var currentDetailViewController: UIViewController!

override viewDidLoad() {
    super.viewDidLoad()
    self.currentDetailViewController = DetailViewController()
}

otherwise, If currentDetailViewController can be nil, you should declare it as an "Optional"

var currentDetailViewController: UIViewController?
like image 105
rintaro Avatar answered Sep 28 '22 03:09

rintaro