如何列出在Swift中实现给定协议的所有类?
说我们有一个例子:
protocol Animal { func speak() } class Cat:Animal { func speak() { print("meow") } } class Dog: Animal { func speak() { print("Av Av!") } } class Horse: Animal { func speak() { print("Hurrrr") } }
这是我当前的(不可编译)方法:
func getClassesImplementingProtocol(p: Protocol) -> [AnyClass] { let classes = objc_getClassList() var ret = [AnyClass]() for cls in classes { if class_conformsToProtocol(cls, p) { ret.append(cls) } } return ret } func objc_getClassList() -> [AnyClass] { let expectedClassCount = objc_getClassList(nil, 0) let allClasses = UnsafeMutablePointer<AnyClass?>.alloc(Int(expectedClassCount)) let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass?>(allClasses) let actualClassCount:Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount) var classes = [AnyClass]() for i in 0 ..< actualClassCount { if let currentClass: AnyClass = allClasses[Int(i)] { classes.append(currentClass) } } allClasses.dealloc(Int(expectedClassCount)) return classes }
但是当打电话给
getClassesImplementingProtocol(Animal.Protocol) 要么
getClassesImplementingProtocol(Animal.Protocol)
getClassesImplementingProtocol(Animal) 要么
getClassesImplementingProtocol(Animal)
getClassesImplementingProtocol(Animal.self)
导致Xcode错误:无法将类型(Animal.Protocol).Type的值转换为预期的参数类型’Protocol’。
有人设法使这个工作正常吗?
由于您使用的是Objective-C运行时来获取类型自省,因此需要以@objc这种方式添加到代码中:
@objc
@objc protocol Animal { func speak() } class Cat:Animal { @objc func speak() { print("meow") } } class Dog: Animal { @objc func speak() { print("Av Av!") } } class Horse: Animal { @objc func speak() { print("Hurrrr") } }
请注意,这种类型的自省可能非常慢。