如何在 Swift 中检查实例的类型?

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

我想使用 unwind segue 从当前 UIViewController 导航到第二个呈现 UIViewController:

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

但是这不起作用。我也尝试将 case 语句更改为 UIViewControllerSubclass.Type 但它给了我一个错误:cast from UIViewController to unrelated type UIViewControllerSubclass always fails.

如果有人能告诉我我做错了什么,我将不胜感激。

您的代码检查类型是正确的:

case is UIViewControllerSubclass:

另一种测试方法 class:

case let vc as UIViewControllerSubclass:

如果您需要访问某个方法或 属性 特定于 class 的方法,这将很有帮助。

如果您不需要使用 vc 则只需执行:

case _ as UIViewControllerSubclass:

您可以在此处使用 if 语句:

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