在swift中实现objectivec协议

时间:2015-11-17 07:28:41

标签: ios objective-c swift

我试图在swift中使用Objective-C实现这个可选的协议方法:

- (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则会出错(CVaListPointer不能在Objective-C中表示)

问题是这个测试失败了:

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

并且不调用swift方法

1 个答案:

答案 0 :(得分:0)

如果你想在swift类中使用objective-c @protocol,你可以在你的swift项目中使用objective-c文件时将X-meta创建的Bridging-Header文件导入objective-c类。那么显然你必须在swift文件中添加委托,你必须在那里使用它。

class classname : baseClass<yourDelegate> {

}

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

但是如果你想从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
相关问题