我目前正在编写一个框架来为我的 OS X 应用程序创建插件。这些插件作为 NSBundle
加载,bundle 的 principalClass
用于运行插件代码。但是,我不知道如何声明 principalClass
对象符合我的协议(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
}
}
声明它符合此协议(protocol)的正确语法是什么?
(此外,此协议(protocol)声明为 @objc
,所以我不确定为什么它说“非@objc”协议(protocol)。)
最佳答案
尝试:bundleClass as MyProtocol.Protocol
。文档 here .
顺便说一句,你的代码可以简化
let bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, NSURL(fileURLWithPath: bundleDirectory), "bundle") as NSArray
for bundle in bundles {
if let loadedClass = bundle.principalClass as? MyProtocol.Protocol {
// ...
}
}
关于Swift 声明 AnyClass 对象实现协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321872/