objective-c - 从 Objective-C 协议(protocol)实例匹配 Swift 协议(protocol)

标签 objective-c swift bridging

我正在寻找一种方法来动态匹配 Objective-C Protocol 实例与相应的 Swift 协议(protocol)。

我在 swift 中定义了一个与 Objective-C 兼容的协议(protocol):

@objc(YHMyProtocol) protocol MyProtocol { }

我尝试在函数中执行匹配:

public func existMatch(_ meta: Protocol) -> Bool {
    // Not working
    if meta is MyProtocol {
        return true
    }

    // Not working also
    if meta is MyProtocol.Protocol {
        return true
    }

    return false
}

此函数旨在从 Objective-C 文件中调用:

if([Matcher existMatch:@protocol(YHMyProtocol)]) {
    /* Do Something */
}

existMatch 函数总是返回 false。

我不知道如何解决这个问题。我在实现过程中遗漏了什么吗?

最佳答案

Protocol 是一个不透明的对象类型。它在生成的 header 中定义为:

// All methods of class Protocol are unavailable. 
// Use the functions in objc/runtime.h instead.

OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0)
@interface Protocol : NSObject
@end

它不符合MyProtocol,所以is MyProtocol不能工作。而且,尽管 Swift 可以隐式地将 @objc 协议(protocol)元类型桥接到 Protocol,但它似乎不能反过来;这就是为什么 is MyProtocol.Protocol 不起作用(但即使它起作用,它也不适用于 derived 协议(protocol);如 P.Protocol 类型目前只能保存值 P.self).

如果你想检查 meta 是等同于或派生自 MyProtocol 的协议(protocol)类型,你可以使用 Obj-C 运行时函数 protocol_conformsToProtocol :

@objc(YHMyProtocol) protocol MyProtocol { }
@objc protocol DerviedMyProtocol : MyProtocol {}

@objc class Matcher : NSObject {
    @objc public class func existMatch(_ meta: Protocol) -> Bool {
        return protocol_conformsToProtocol(meta, MyProtocol.self)
    }
}

// the following Swift protocol types get implicitly bridged to Protocol instances
// when calling from Obj-C, @protocol gives you an equivalent Protocol instance.
print(Matcher.existMatch(MyProtocol.self)) // true
print(Matcher.existMatch(DerviedMyProtocol.self)) // true

如果您只是想检查meta是否等同于MyProtocol,您可以使用protocol_isEqual:

@objc class Matcher : NSObject {
    @objc public class func existMatch(_ meta: Protocol) -> Bool {
        return protocol_isEqual(meta, MyProtocol.self)
    }
}

print(Matcher.existMatch(MyProtocol.self)) // true
print(Matcher.existMatch(DerviedMyProtocol.self)) // false

关于objective-c - 从 Objective-C 协议(protocol)实例匹配 Swift 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45011413/

相关文章:

ios - Google+ iOS SDK 获取好友列表?

ios - AFMultipartFormData 上传完成后运行方法

iphone - ios4 中不显示外部视频

ios - 区分 UITableViewCell 上的单击和双击

swift - 如何验证服务器端 Swift HTTPS 端点中的 SNS 消息?

objective-c - NSInvalidArgumentException 问题

ios - 如何计算标签的最后一行宽度?

objective-c - Objective C 接口(interface)生成的头文件无法导入到其他头文件中

objective-c - UIColor swift 扩展 w/来自 Objective-C 的类访问