は、不透明なオブジェクトタイプです。それはMyProtocol
に準拠していないので、is MyProtocol
が動作しないことができる
// 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
:それは次のように生成されたヘッダで定義されています。また、Swiftは暗黙的に@objc
プロトコルのメタタイプをProtocol
に橋渡しすることができますが、逆を行うことはできません。これはis MyProtocol.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
おそらく関連:[プロトコル自体に準拠していません?] (https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself)。 –
'meta'が厳密に' MyProtocol'に相当するのか、それとも 'MyProtocol'から派生しているのか確認しますか? – Hamish
私はmetaが互換性があるか/ MyProtocolに準拠しているかどうかテストしたいと思っています – yageek