How to list all classes conforming to protocol in Swift?
Since you're using the Objective-C runtime to get the type introspection you need to add @objc
to your code in this manner:
@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") }}
Note that this kind of type introspection might be very slow.
In terms of speed, you can do it in a single for, and avoid having to iterate through all classes like so:
func getClassesConformingProtocol(p: Protocol)-> [AnyClass]{ let expectedClassCount = objc_getClassList(nil, 0) let allClasses = UnsafeMutablePointer<AnyClass>.allocate(capacity: Int(expectedClassCount)) let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass>(allClasses) let actualClassCount:Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount) var classes = [AnyClass]() for i in 0 ..< actualClassCount { let currentClass = allClasses[Int(i)] if class_conformsToProtocol(currentClass, p) { classes.append(currentClass) } } return classes}