I have a protocol that's defined in Objective-C, like:
@protocol MyProtocol <NSObject>
- (void)doStuffWithDictionary:(NSDictionary*)dict
andString:(NSString*)str1
andOptionalString:(NSString*)str2
andOptionalArray:(NSArray*)arr
callback:(void (^)(id result))onSuccess;
@end
...and I'm trying to define a class in Swift that implements this protocol, like:
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)! {
...
}
}
However I'm getting build errors along the lines of:
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)!
It appears to be upset about the andOptionalArray arr: NSArray? = nil
andOptionalArray arr: NSArray? = nil
parameter. What is the correct syntax to use here?
I put your protocol in a project and imported it in <ProjectName>-Bridging-Header.h
, and Auto Complete suggested this syntax:
public func doStuff(with dict: [AnyHashable : Any],
andString str1: String,
andOptionalString str2: String,
andOptionalArray arr: [Any],
callback onSuccess: @escaping (Any) -> Void) {
}
If you want the String
and [Any]
to be imported as optional, you need to mark them as nullable
in Objective-C:
@protocol MyProtocol <NSObject>
- (void)doStuffWithDictionary:(NSDictionary*)dict
andString:(NSString*)str1
andOptionalString:(nullable NSString*)str2
andOptionalArray:(nullable NSArray*)arr
callback:(void (^)(id result))onSuccess;
@end
As @MartinR suggested in the comments:
Go to the header file where the protocol is defined, and choose "Generated Interface" from the "Related Items" popup in the top-left corner. That will show you the exact Swift method signature that you have to implement.
This works too and offers different interfaces for different versions of Swift.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.