簡體   English   中英

從Objective-C協議實例匹配Swift協議

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM