5
votes

I'm trying to implement this optional protocol method from Objective-C in swift :

- (void)customHTTPProtocol:(CustomHTTPProtocol *)protocol logWithFormat:
(NSString *)format arguments:(va_list)arguments;

( cfr: https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/Introduction/Intro.html ) I have written this method in swift :

func customHTTPProtocol(`protocol`: CustomHTTPProtocol!, logWithFormat format: String!, arguments: CVaListPointer) {
}

it complains that cannot satisfy optional requirement and suggests to add a @objc before method , but if I add @objc it gives an error ( CVaListPointer cannot be represented in Objective-C )

The problem is that this test fails:

if ([strongDelegate respondsToSelector:@selector(customHTTPProtocol:logWithFormat:arguments:)]) {

and the swift method is not called

1

1 Answers

0
votes

If you want to use objective-c @protocol in swift class then you have import objective-c class into your Bridging-Header file which is created by XCode when you use objective-c file in your swift project. Then obviously you have to add the delegate in the swift file where you have to use it like.

class classname : baseClass<yourDelegate> {

}

In this file first you have to add all the required delegate methods and then add the optional method you have to use. If you do not add the required delegate method then it gives you error.

However if you want to use protocol from swift to objective-c then you have to add @objc before protocol name and to import swift file to objective-c file, you have also add @objc before class like this,

@objc protocol DelegateName {
    //declare your required and optional delegate method here
}

@objc classname : baseClass<yourDelegate> {

}

And then import your swift class into your objective-c file like this,

#import <PROJ_NAME/PROJ_DIR-Swift.h>

And the important thing to add :

classObj.delegate = self