检查对象是否是Swift中给定的泛型类型



navigationController中有一个viewControllers数组,我需要找到特定的vc并调用popToViewController方法。但是类型检查总是失败。

如何在Swift中检查vc是否为给定类型?

func popToViewController<T>(vcClass: T.Type, animated: Bool) {
guard let mainVc = self.rootController else {
return
}
let controllers = mainVc.viewControllers
for vc in controllers {
if vc is T  {   // always is false 
_ = mainVc.popToViewController(vc , animated: true)
}
}
}
self?.router.popToViewController(vcClass: ViewController1.Type.self, animated: true)

试试这个:

if type(of: vc) == T.self {
_ = mainVc.popToViewController(vc , animated: true)
}

或者,如果您想检查可以转换为T:的vc

if let _ = vc as? T {
_ = mainVc.popToViewController(vc , animated: true)
}

最新更新