ios - 将 ViewController 与 swift 中的类型进行比较

标签 ios swift generics uiviewcontroller comparison

extension UIViewController {
    func getChildViewController<T>(OfType: T) {
        let classType = Mirror(reflecting: self.childViewControllers.first).subjectType

        if classType == T.self {
            print("there is a match")
        }
    }
}

这是对 UIViewController 的扩展,当你调用这个函数时,你传递给它一个类型,例如:

ViewController.getChildViewController(OfType: SecondViewController.self)

这将检查 View Controller 的第一个子节点是否为 SecondViewController 类型

但是在 if 语句中我得到了错误:

Binary operator '==' cannot be applied to operands of type 'Any.Type' and 'T'

最佳答案

Swift 3 中的 isKindOf 只是 is 所以你应该使用像这样的东西:

if classType is SecondViewController {
   print("there is a match")
}

关于ios - 将 ViewController 与 swift 中的类型进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41671049/

相关文章:

ios - 在 Xcode 中打开我的 React Native 项目,我的代码在哪里?

ios - CloudKit在保存信息时总是遇到错误Swift 2

c# - 如何获取泛型类的名称?

java - Java中的泛型方法,判断类型

c# - 在没有新约束的情况下创建 T 的新实例

ios - 如何在 tableview 单元格内的 collectionview 单元格的按钮单击上获取索引

ios - Realm:查询具有相同属性的对象

html - 将属性字符串转换为 "simple"标记的 html

swift - 使用 json 序列化的 void 函数 swift 4 中出现意外的非 void 返回值

objective-c - 使用 NSPredicate 的位置之间的距离