Search code examples
iosswiftunwind-segue

How can I check an instance's type in Swift?


I want to use an unwind segue to navigate from the current UIViewController to the second presenting UIViewController:

let unwindDestinationViewController = self.presentingViewController!.presentingViewController!
                    switch unwindDestinationViewController{
                    case is UIViewControllerSubclass:
                        self.performSegue(withIdentifier: "unwindToUIViewControllerSubclass", sender: self)
                        break
                    default:
                        break
                    }

However this does not work. I also tried changing the case statement to UIViewControllerSubclass.Type but it gave me an error: cast from UIViewController to unrelated type UIViewControllerSubclass always fails.

I'd really appreciate if someone could tell me what I am doing wrong.


Solution

  • Your code is correct for checking the type:

    case is UIViewControllerSubclass:
    

    Another way to test the class:

    case let vc as UIViewControllerSubclass:
    

    which is helpful if you need to access a method or property specific to that class.

    If you don't need to use vc then just do:

    case _ as UIViewControllerSubclass:
    

    You could just use an if statement here:

    if unwindDestinationViewController is UIViewControllerSubclass {
        self.performSegue(withIdentifier: "unwindToUIViewControllerSubclass", sender: self)
    }