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

时间:2017-08-09 06:30:46

标签: swift generics swift3

如何将objectAnyClass泛型类型进行比较:

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

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

checkGeneric(className: UIViewController.self)

2 个答案:

答案 0 :(得分:1)

你也可以用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

答案 1 :(得分:0)

试试这个

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)