Swift – Could not cast value of type ‘UINavigationController’

swiftxcode

I am implementing a search interface for my application, so basically I will pass the search keyword from one ViewController to another ViewController.

I have done this type of parameter passing several times but something seems strange this time. The destination ViewController is embedded in a Navigation Controller.

Now the code looks something like this.

override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject!) {
    if (segue?.identifier == "home_to_search") {

       var searchKeyword = txtSearchBarHome.text
       var svc = segue?.destinationViewController as! SearchViewController;
       svc.toPassSearchKeyword = searchKeyword;

       //let nav = segue?.destinationViewController as! UINavigationController
       //let svc = nav.topViewController as! SearchViewController
       //svc.toPassSearchKeyword = searchKeyword;
    }
}

I have already explored these questions
DestinationViewController Segue and UINavigationController swift, How do I segue values when my ViewController is embedded in an UINavigationController? with no luck.

What makes me wonder is that I already have ViewControllers embedded in Navigation Controllers that I can pass parameters by segueing. However, in this case it throws a Could not cast value of type 'UINavigationController' error. If I try the commented code above it does not throw an error there, but at the AppDelegate class.

Best Answer

Answering my own question. In this case we need to access the child view by doing something like this:

let nav = segue?.destinationViewController as! UINavigationController
let svc = nav.topViewController as! SearchViewController
svc.toPassSearchKeyword = searchKeyword;