Search code examples
swiftcastinguiviewcontrollerdowncast

Upcast ViewControllers for Segues


I have two views, A and B, both inheriting from C.

In storyboard, I define a UIViewController as type C.

Another view, lets say D, has two segues to C.

I want to be able to cast the destination according to the relevant segue:

if segue.identifier = "ToA"
{
   // Load view A
}
if segue.identifier = "ToB"
{
   // Load view B
}

I have tried it and casting fails. Is it possible?

I found another thread here on SO that says it is not, yet there was a reply there saying it is possible. How can I make this casting work?

Or should I just fuse A and B together? I really don't want to do that.


Solution

  • This is not possible, since inheritance does not work like this. A and B are also C. But C is neither A nor B. And C is what is initialized and pushed/presented/embedded when you perform your segues.

    You need to create two different ViewControllers A and B in your storyboard. They can have some IBOutlet/IBAction connections to your C.swift file.