Swift declare that AnyClass object implements protocol

时间秒杀一切 提交于 2019-12-12 02:06:44

问题


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:


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 {
        // ...
    }
}


来源:https://stackoverflow.com/questions/27321872/swift-declare-that-anyclass-object-implements-protocol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!