繁体   English   中英

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

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

我想使用展开搜索从当前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:

测试类的另一种方法:

case let vc as UIViewControllerSubclass:

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

如果您不需要使用vc ,请执行以下操作:

case _ as UIViewControllerSubclass:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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