我可以返回一个类的所有子类的列表吗?例如:
class Mother { } class ChildFoo: Mother { } class ChildBar: Mother { } let motherSubclasses = ... // TODO print(motherSubclasses) // should to return [ChildFoo.self,ChildBar.self]
令人惊讶的是,Objective-C运行时函数与Swift类一样工作,即使它们不是NSObject的子类.此外,Swift中的所有类似乎都是从SwiftObject派生的. SwiftObject本身没有超类.
首先,一个处理ObjC运行时函数的包装器结构:
import Foundation struct ClassInfo : CustomStringConvertible,Equatable { let classObject: AnyClass let className: String init?(_ classObject: AnyClass?) { guard classObject != nil else { return nil } self.classObject = classObject! let cName = class_getName(classObject)! self.className = String(cString: cName) } var superclassInfo: ClassInfo? { let superclassObject: AnyClass? = class_getSuperclass(self.classObject) return ClassInfo(superclassObject) } var description: String { return self.className } static func ==(lhs: ClassInfo,rhs: ClassInfo) -> Bool { return lhs.className == rhs.className } }
以下是如何使用它:
class Mother { } class ChildFoo: Mother { } class ChildBar: Mother { } class AnIrrelevantClass { } let motherClassInfo = ClassInfo(Mother.self)! var subclassList = [ClassInfo]() var count = UInt32(0) let classList = objc_copyClassList(&count)! for i in 0..<Int(count) { if let classInfo = ClassInfo(classList[i]),let superclassInfo = classInfo.superclassInfo,superclassInfo == motherClassInfo { subclassList.append(classInfo) } } print(subclassList)
这只会进行浅层搜索,因此它不会扫除孙子类,但你明白了.