wqyfavor
wqyfavor

Reputation: 539

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?

Upvotes: 2

Views: 394

Answers (1)

JAL
JAL

Reputation: 42449

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)

In Swift 3, depending on the way the class is bridged to Swift, your function might look like this:

MyClass.proxy(with: AProtocol)
MyClass.proxy(with: MyProtocol)

Although the compiler isn't happy with the location of "with" and may complain.

Upvotes: 2

Related Questions