0

Is it possible to get the name of all the implementers of a swift protocol..? and if it is then how..?

I am trying to write and SDK which exposes a protocol which has all the static methods, I do not want to implement delegate pattern here as I want to get the name of all the implementers and call the methods directly.

Nilesh
  • 1,493
  • 18
  • 29
  • whats the whole point of having protocols if you dont have delegates (weak reference to class which implements your protocol) ? How do you plan to get all objects in memory? and call method manually – Sandeep Bhandari Jul 28 '18 at 17:02
  • Please don't fight the framework – vadian Jul 28 '18 at 17:20
  • Thank you for replying guys, I do understand that this would be horrible design to go with bit i am doing some sort of experiment and i was wondering if it is possible and how. So I found one old similar question : https://stackoverflow.com/questions/34415028/how-to-list-all-classes-conforming-to-protocol-in-swift Which kinda works. Thank you – Nilesh Aug 14 '18 at 08:21

1 Answers1

1

so this is how I did it:

static func getClassesImplementingProtocol(_ protocolName: Protocol!) -> [AnyClass] {

    var result = [AnyClass]();

    let count: Int32 = objc_getClassList(nil, 0)

    guard count > 0 else {
        return result
    }

    let classes = UnsafeMutablePointer<AnyClass>.allocate(
        capacity: Int(count)
    )

    defer {
        classes.deallocate()
    }

    let buffer = AutoreleasingUnsafeMutablePointer<AnyClass>(classes)

    for i in 0..<Int(objc_getClassList(buffer, count)) {
        let someclass: AnyClass = classes[i]

        if class_conformsToProtocol(someclass, protocolName) {

            result.append(someclass);
        }
    }

    return result
}

Thanks to : How to list all classes conforming to protocol in Swift?

Nilesh
  • 1,493
  • 18
  • 29