Swift 声明 AnyClass 对象实现协议 [英] Swift declare that AnyClass object implements protocol
问题描述
我目前正在编写一个框架,用于为我的 OS X 应用程序创建插件.这些插件作为 NSBundle
加载,并且包的 principalClass
用于运行插件代码.但是,我不知道如何声明 principalClass
对象符合我的协议.
I am currently writing a framework for creating plugins for my OS X application. These plugins are loaded as NSBundle
s, and the bundles' principalClass
es 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
}
}
声明它符合这个协议的正确语法是什么?(另外,这个协议被声明为 @objc
所以我不知道为什么它说非@objc"协议.)
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.)
推荐答案
尝试:bundleClass as MyProtocol.Protocol
.文档 此处.
顺便说一句,你的代码可以简化
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 {
// ...
}
}
这篇关于Swift 声明 AnyClass 对象实现协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!