【问题标题】:Swift declare that AnyClass object implements protocolSwift 声明 AnyClass 对象实现协议
【发布时间】:2014-12-06 02:55:32
【问题描述】:

我目前正在编写一个框架来为我的 OS X 应用程序创建插件。这些插件被加载为NSBundles,并且捆绑包的principalClasses 用于运行插件代码。但是,我不知道如何声明 principalClass 对象符合我的协议。

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”协议。)

【问题讨论】:

    标签: swift protocols


    【解决方案1】:

    试试: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 4中使用MyProtocol.Type
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多