我正在尝试从Objective-C快速实现此可选协议(protocol)方法:

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

(cfr:https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/Introduction/Intro.html)
我已 swift 编写了此方法:
func customHTTPProtocol(`protocol`: CustomHTTPProtocol!, logWithFormat format: String!, arguments: CVaListPointer) {
}

它提示不能满足可选要求,并建议在方法之前添加@objc,但是如果我添加@objc,则会出现错误(无法在Objective-C中表示CVaListPointer)

问题是此测试失败:
if ([strongDelegate respondsToSelector:@selector(customHTTPProtocol:logWithFormat:arguments:)]) {

并没有调用swift方法

最佳答案

如果要在swift类中使用Objective-C @protocol,则需要将Objective-C类导入到XCode在swift项目中使用Objective-C文件时创建的Bridging-Header文件中。那么显然您必须在需要使用它的swift文件中添加委托(delegate)。

class classname : baseClass<yourDelegate> {

}

在此文件中,首先必须添加所有必需的委托(delegate)方法,然后添加必须使用的可选方法。如果您不添加所需的委托(delegate)方法,那么它将给您错误。

但是,如果您想从swift到Objective-c使用protocol,则必须在protocol名称之前添加@objc并将swift文件导入到Objective-c文件,您还必须在此类之前添加@objc,
@objc protocol DelegateName {
    //declare your required and optional delegate method here
}

@objc classname : baseClass<yourDelegate> {

}

然后像这样将您的swift类导入到您的Objective-C文件中,
#import <PROJ_NAME/PROJ_DIR-Swift.h>

重要的是要添加:
classObj.delegate = self

关于ios - 快速实现Objectivec协议(protocol),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33751351/

10-12 00:22
查看更多