【问题标题】:Checking if an object is a given generic type in Swift [duplicate]在 Swift 中检查对象是否是给定的泛型类型
【发布时间】:2021-02-06 08:28:58
【问题描述】:

我在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)

【问题讨论】:

    标签: swift type-inference typechecking generic-type-argument


    【解决方案1】:

    试试这个:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 2017-12-06
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 2011-03-06
      • 1970-01-01
      相关资源
      最近更新 更多