wqyfavor wqyfavor - 5 months ago 24
Swift Question

Pass @protocol type in Swift

I have an Objective-C method which takes Protocol* type as parameter.

How can I invoke this method in Swift.

Example:

// In Objective-C

@protocol AProtocol <NSObject>
@end

@interface MyClass : NSObject
+ (id)proxyWithProtocol:(Protocol*)protocol;
@end

// I can call this method with a protocol as parameter
[MyClass proxyWithProtocol:@protocol(AProtocol)];


If I want to use MyClass in Swift by bridging. How can I pass a protocol defined in Objective-C to proxyWithProtocol method. Can I even pass a protocol defined in Swift to this method?

JAL JAL
Answer

You would pass the Objective-C protocol in like so:

MyClass.proxyWithProtocol(AProtocol)

If you wanted to pass in a Swift protocol, you would have to expose that protocol to Objective-C:

@objc protocol MyProtocol {
    func someGreatFunc()
}

// ...

MyClass.proxyWithProtocol(MyProtocol)