Swift View Controller Downcasting

191 views Asked by At

I thought the following would populate my home variable with my HomeViewController

var home = self.parentViewController!.parentViewController! as HomeViewController;

Instead I get the following compile error 'Use of undeclared type HomeViewController' although it definitely exists and appears in the auto complete popup.

3

There are 3 answers

4
cmyr On

Often XCode6 displays the wrong error message. Is this an instance variable? It may be that parentViewController isn't set at init time (the fact that it's an implicitly unwrapped optional strongly suggests this). If this is in a function, I'd do this in an if let statement to give us a better sense of what's going on. Something like:

if let homeVC = self.parentViewController?.parentViewController as? HomeViewController {
    self.home = homeVC
}

This would give us at least a better opportunity to debug. Two !s in a row maybe means you're not being totally respectful of what those declarations are trying to tell you.

0
Ben_hawk On

The cause of this error was actually coming from a bug in xcode 6 rather than any kind of syntax error. It was related to this: Xcode 6 Strange Bug: Unknown class in Interface Builder file

I was able to fix this by clearing the projects derived data and build and restarting my machine.

0
anoop4real On

I had faced the same problem while doing an unwind segue and trying to downcast the sourceviewcontroller. I bang my head for more than 30mins and then I realized it was fairly simple and bit crazy, I had all my files except this viewcontroller added to the Tests target and after adding this viewcontroller to the Tests target, everything worked Tada!! I m saved.