Search code examples
iosswiftuiviewcontrollerstoryboardinstantiation

How to create subclass view controller whose base class has storyboard?


I have a storyboard-based UIViewController called BaseViewController which has the same name as ID.

I have a simple subclass MyViewController : BaseViewController (which has no storyboard nor XIB).

I want to create a MyViewController such that it instantiates its base class BaseViewController from the storyboard.

I tried the following code:

let storyboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "BaseViewController") as! MyViewController

Which of course, as pointed out by Sh_Khan in answer below, doesn't work and results in: Could not cast value of type 'myProject.BaseViewController' (0x...) to 'myProject.MyViewController' (0x...).

How then can I create a MyViewController object?


Solution

  • You can up cast meaning cast from child to parent but not vice versa the reason is simple child has all related data to parent so it can go to it easily but the parent doesn't know what the child has