简体   繁体   中英

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM