class Mother {}class ChildFoo: Mother {}class Childbar: Mother {}let motherSubclasses = ... // Todoprint(motherSubclasses) // should to return [ChildFoo.self,Childbar.self]令人惊讶的是,Objective-C运行时函数与Swift类一样工作,即使它们不是NSObject的子类.此外,Swift中的所有类似乎都是从SwiftObject派生的. SwiftObject本身没有超类.
首先,一个处理ObjC运行时函数的包装器结构:
import Foundationstruct 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)
这只会进行浅层搜索,因此它不会扫除孙子类,但你明白了.
总结以上是内存溢出为你收集整理的swift – 列出一个类的所有子类全部内容,希望文章能够帮你解决swift – 列出一个类的所有子类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)