swift - Initialize view controller from storyboard by overriding init

adamF picture adamF · Aug 5, 2015 · Viewed 17.9k times · Source

I have a ViewController instance defined in a storyboard. I can initialize it by the following

var myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("myViewControllerIdentifier") as! ViewController

Is there a way to override the init method of ViewController so that I can initialize it using

var myViewController = ViewController()

I tried overriding init

convenience init() {
    self = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SearchTableViewController") as! SearchTableViewController
}

but the compiler doesn't like that. Any ideas?

Answer

Steven McGrath picture Steven McGrath · Aug 5, 2015

A convenience initializer must always delegate to a designated initializer for the same class, and a designated initializer must call a superclass initializer.

Since the superclass doesn't have an appropriate initializer, you would probably be better served by a class factory method:

static func instantiate() -> SearchTableViewController
{
    return UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SearchTableViewController") as! SearchTableViewController
}

then use:

var myViewController = SearchTableViewController.instantiate()