我有一个在Objective-C中定义的协议,例如:
@protocol MyProtocol <NSObject>
- (void)doStuffWithDictionary:(NSDictionary*)dict
andString:(NSString*)str1
andOptionalString:(NSString*)str2
andOptionalArray:(NSArray*)arr
callback:(void (^)(id result))onSuccess;
@end
...并且我正在尝试在Swift中定义一个实现此协议的类,例如:
class MyImpl : Operation, MyProtocol {
func doStuff(withDictionary dict: [AnyHashable : Any]!,
andString str1: String!,
andOptionalString str2: String? = nil,
andOptionalArray arr: NSArray? = nil,
callback onSuccess: ((Any?) -> Void)! {
...
}
}
但是我遇到以下错误:
Type 'MyImpl' does not conform to protocol 'MyProtocol'
note: candidate has non-matching type '([AnyHashable : Any]!, String!, String?, NSArray?, ((Any?) -> Void)!'
func doStuff(withDictionary dict: [AnyHashable : Any]!, andString str1: String!, andOptionalString str2: String? = nil, andOptionalArray arr: NSArray? = nil, callback onSuccess: ((Any?) -> Void)!
对于andOptionalArray arr: NSArray? = nil
参数似乎很沮丧。在这里使用正确的语法是什么?
答案 0 :(得分:1)
我将您的协议放入一个项目中,并将其导入 <div class="row clearfix">
<div class="col-lg-3 col-md-6 col-sm-12 mb-30 parent" (click)="click(item)" *ngFor="let item of services">
<div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child" [ngClass]="item.isFirstChild ? 'apply-opacity' : ''">
<div style="margin-top: 30px">
<i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
</div>
<h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
</div>
</div>
</div>
中,并且自动完成建议使用以下语法:
<ProjectName>-Bridging-Header.h
如果要将public func doStuff(with dict: [AnyHashable : Any],
andString str1: String,
andOptionalString str2: String,
andOptionalArray arr: [Any],
callback onSuccess: @escaping (Any) -> Void) {
}
和String
导入为可选,则需要在Objective-C中将它们标记为[Any]
:
nullable
如@MartinR在评论中所建议:
转到定义协议的头文件,然后从左上角的“相关项目”弹出窗口中选择“生成的接口”。这将向您显示您必须实现的确切Swift方法签名。
这也适用,并为不同版本的Swift提供不同的界面。