检查对象是否为Swift中给定的泛型类型
我在navigationController中有一个ViewController数组,我需要找到特定的vc并调用popToViewController方法。但是类型检查总是失败 如何在Swift中检查vc是否属于给定类型检查对象是否为Swift中给定的泛型类型,swift,type-inference,typechecking,generic-type-argument,Swift,Type Inference,Typechecking,Generic Type Argument,我在navigationController中有一个ViewController数组,我需要找到特定的vc并调用popToViewController方法。但是类型检查总是失败 如何在Swift中检查vc是否属于给定类型 func popToViewController<T>(vcClass: T.Type, animated: Bool) { guard let mainVc = self.rootController else { retu
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)
}
}
}
试试这个:
if type(of: vc) == T.self {
_ = mainVc.popToViewController(vc , animated: true)
}
或者,如果您想检查可转换到T
中的vc
:
if let _ = vc as? T {
_ = mainVc.popToViewController(vc , animated: true)
}
if let _ = vc as? T {
_ = mainVc.popToViewController(vc , animated: true)
}