如何将object
与AnyClass
泛型类型进行比较:
我想将一个对象与类的类型进行比较,并且类名应该作为参数传递。
func checkGeneric(className: AnyClass) {
let object = UIViewController()
if (object is className) { // Use of undeclared type `className`
print(className)
}
}
checkGeneric(className: UIViewController.self)
答案 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)