使用未声明的类型错误:如何比较对象与类类型?
问题描述:
如何使用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)
}
}
答
您还可以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)
谢谢它的作品:) –