Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all classes conforming to protocol in Swift?

Tags:

People also ask

How many protocols can a Swift class adopt?

Swift 4 allows multiple protocols to be called at once with the help of protocol composition.

What is class protocol in Swift?

In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). We use the protocol keyword to define a protocol. For example, protocol Greet { // blueprint of a property var name: String { get } // blueprint of a method func message() }

What's the difference between a protocol and a class in Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

CAN protocol inherit from class Swift?

Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on class , struct , and enum types. Only class types can use base classes and inheritance from a protocol.


How to list all classes implementing a given protocol in Swift?

Say we have an example:

protocol Animal {     func speak() }  class Cat:Animal {     func speak() {         print("meow")     } }  class Dog: Animal {     func speak() {         print("Av Av!")     } }  class Horse: Animal {     func speak() {         print("Hurrrr")     } } 

Here is my current (not compilable) approach:

func getClassesImplementingProtocol(p: Protocol) -> [AnyClass] {     let classes = objc_getClassList()     var ret = [AnyClass]()      for cls in classes {         if class_conformsToProtocol(cls, p) {             ret.append(cls)         }     }     return ret }  func objc_getClassList() -> [AnyClass] {     let expectedClassCount = objc_getClassList(nil, 0)     let allClasses = UnsafeMutablePointer<AnyClass?>.alloc(Int(expectedClassCount))     let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass?>(allClasses)     let actualClassCount:Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount)      var classes = [AnyClass]()     for i in 0 ..< actualClassCount {         if let currentClass: AnyClass = allClasses[Int(i)] {             classes.append(currentClass)         }     }      allClasses.dealloc(Int(expectedClassCount))      return classes } 

But when calling either

getClassesImplementingProtocol(Animal.Protocol) or

getClassesImplementingProtocol(Animal) or

getClassesImplementingProtocol(Animal.self)

results in Xcode error: cannot convert value of type (Animal.Protocol).Type to expected argument type 'Protocol'.

Did anyone manage get this working?