Last active
March 10, 2020 10:58
-
-
Save hcn1519/1cfb73425a2f82936c989a40d2f84839 to your computer and use it in GitHub Desktop.
Get All SubClass Name in your App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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