Skip to content

Instantly share code, notes, and snippets.

@hcn1519
Last active March 10, 2020 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcn1519/1cfb73425a2f82936c989a40d2f84839 to your computer and use it in GitHub Desktop.
Save hcn1519/1cfb73425a2f82936c989a40d2f84839 to your computer and use it in GitHub Desktop.
Get All SubClass Name in your App
func allSubClass<T>(of targetClass: T, bundle: Bundle) -> [T] {
var count: UInt32 = 0
guard let allClasses = objc_copyClassList(&count) else {
return []
}
let targetClasses: [T] = (0..<count).compactMap { index in
let someClass: AnyClass = allClasses[Int(index)]
guard Bundle(for: someClass) == bundle else { return nil }
guard let someSuperClass = class_getSuperclass(someClass) else { return nil }
guard String(describing: someSuperClass) == String(describing: targetClass) else { return nil }
return someClass as? T
}
return targetClasses
}
// usage
let vc = allSubClass(of: UIViewController.self, bundle: Bundle.main)
let nav = allSubClass(of: UINavigationController.self, bundle: Bundle.main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment