[英]Matching a Swift protocol from an Objective-C Protocol instance
我正在尋找一種方法來動態匹配Objective-C Protocol
實例與相應的Swift協議。
我在swift中定義了一個與Objective-C兼容的協議:
@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
是一種不透明的對象類型。 它在生成的頭文件中定義為:
// 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
無法正常工作。 而且,雖然斯威夫特可以隱橋@objc
協議元類型,以Protocol
,看來,它不能做反向; 這就是為什么is MyProtocol.Protocol
不起作用(但即使它確實如此,它也不適用於派生協議;因為P.Protocol
類型目前只能保持值P.self
)。
如果要檢查meta
是與MyProtocol
等效或派生的協議類型,可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.