Swift 声明 AnyClass 对象实现协议(protocol)

标签 swift protocols

我目前正在编写一个框架来为我的 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/

相关文章:

ios - 为什么 UIColor.white、red、green 和 blue 不工作,但所有其他颜色常量都工作正常?

node.js - 如何让多个 Node.js 命令行进程相互通信?

ios - 将数据从子 VC 传递回 Collection View Cell

swift - 如何在当前类型 Swift 中使用泛型函数

objective-c - WatchKit 接口(interface) : Is it possible to add multiple labels in a tableView group without any of the labels being pushed to the right?

xcode - 如何在 Swift 中以编程方式添加约束

objective-c - 类型 'Boolean' 不符合协议(protocol) 'BooleanType'

swift - 使用 Swift 和组合链接+压缩多个网络请求

ios - 使用 AFNetworking 2.0 创建自己的委托(delegate)和协议(protocol)

json - Argo:类型不符合协议(protocol) 'Decodable'