1
votes

I am currently writing a framework for creating plugins for my OS X application. These plugins are loaded as NSBundles, and the bundles' principalClasses are used to run the plugin code. However, I can't figure out how to declare that the principalClass object conforms to my protocol.

let bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, NSURL(fileURLWithPath: bundleDirectory), "bundle") as NSArray

for bundle in bundles
{
    let bundleClass = bundle.principalClass!!

    if (bundleClass.conformsToProtocol(MyProtocol.self))
    {
        //Produces compiler error:
        //"Cannot downcast from 'AnyClass' to non-@objc protocol type 'MyProtocol'"
        let loadedClass = bundleClass as MyProtocol
    }
}

What is the proper syntax for declaring that it conforms to this protocol? (Also, this protocol is declared @objc so I'm not sure why it says "non-@objc" protocol.)

1

1 Answers

3
votes

try: bundleClass as MyProtocol.Protocol. The docs here.

BTW, your code can be simplified

let bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, NSURL(fileURLWithPath: bundleDirectory), "bundle") as NSArray
for bundle in bundles {
    if let loadedClass = bundle.principalClass as? MyProtocol.Protocol {
        // ...
    }
}