【问题标题】:Use undeclared type error: How to compare object with class type?使用未声明的类型错误:如何将对象与类类型进行比较?
【发布时间】:2017-08-09 06:30:46
【问题描述】:

如何比较objectAnyClass 泛型类型:

我想将一个对象与类的类型进行比较,并且类名应该作为参数传递。

func checkGeneric(className: AnyClass) {
    let object = UIViewController()
    if (object is className) { // Use of undeclared type `className`
        print(className)
    }
}

checkGeneric(className: UIViewController.self)

【问题讨论】:

    标签: swift generics swift3


    【解决方案1】:

    您可以使用type(of:) 获取object 的类型并将其与AnyClass 进行比较。试试这个..

    func checkGeneric(className: AnyClass) {
        let object = UIViewController()
        if (type(of: object) == className) { // Use of undeclared type class name
            print(className)
        }
    }
    

    【讨论】:

      【解决方案2】:

      你也可以用 isKinOf 做到这一点

      func checkGeneric(className: AnyClass)
          {
              print(className)
              let object = UIViewController()
              if object.isKind(of: className) {
                  print("yes")
              } else {
                  print("no")
              }
      
          }
      
          checkGeneric(className: UIViewController.self)
          checkGeneric(className: NSMutableArray.self)
      

      输出

      UIViewController
      yes
      NSMutableArray
      no
      

      【讨论】:

        【解决方案3】:

        试试这个

        func checkGeneric(className: AnyClass) {
            let object = ViewController()
            if (object.isKind(of: className)) {
                print("Class Name is : \(className)")
            }
        }
        
        checkGeneric(className: ViewController.self)
        

        您可以使用 isKind() 将对象与类进行比较,

        let viewController = UIViewController()
        
        viewController.isKind(of: ViewController.self)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 2013-09-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多