使用未声明的类型错误:如何比较对象与类类型?

使用未声明的类型错误:如何比较对象与类类型?

问题描述:

如何使用AnyClass泛型类型比较object使用未声明的类型错误:如何比较对象与类类型?

我想比较类的类型和类名称的对象应该作为参数传递。

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

checkGeneric(className: UIViewController.self) 

您可以使用type(of:)得到object的类型,并将其与AnyClass比较。试试这个..

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

谢谢它的作品:) –

您还可以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) 

OUPUT做

UIViewController 
yes 
NSMutableArray 
no 
+0

这也适用我欣赏:) –

试试这个

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

checkGeneric(className: ViewController.self) 

您可以比较C对象lass使用isKind(),

let viewController = UIViewController() 

viewController.isKind(of: ViewController.self)