Running ObjC Protocol in Swift

Well, here is a big problem. I had a library written in ObjC ( this ). There we had a certain protocol. When I tried to use it in a fast file, I constantly:

Type "XXX" does not comply with protocol "XXX"

To simplify things, I made a test project - it should be created as a Swift project.

Then create an ObjC header file (I named it StupidProtocol.h) with the following protocol inside (pay attention to each name and value to exactly match the data, including upper or lower case):

@protocol MyProtocol <NSObject> - (NSString *)getAxisLabel:(id)axis Value:(CGFloat)value; @end 

In the header of the bridge:

 #import "StupidProtocol.h" 

And then back to the Swift file:

 class ViewController: UIViewController, MyProtocol { func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! { return "" } } 

And baam, we got this error again, although autocomplete completes the getAxisLabel function for me.

I strongly suspect that the problem is related to the argument "value" and the parameter of the function "Value".

Any help would be greatly appreciated.

EDIT

Please note that this library is not technically mine, so I cannot change it. I need a way to use it in Swift without changing its original declaration. My example is just to simplify my problem.

WHAT DID I SAY

I tried the following scripts without success:

'has different argument names from those required by the' error 'protocol

 func getAxisLabel(axis: AnyObject!, Value value: CGFloat) -> String! { return "" } 

'has different argument names from those required by the' error 'protocol

 func getAxisLabel(axis: AnyObject!, Value: CGFloat) -> String! { return "" } 

'does not comply with protocol

 func getAxisLabel(axis: AnyObject!, Value: CGFloat) -> NSString! { return "" } 

DECISION

See accepted answer

+6
source share
1 answer

I do not know if this is a mistake or not. Objective-C Protocol Method

 - (NSString *)getAxisLabel:(id)axis Value:(CGFloat)value; 

(with an uppercase "V" in Value: displayed in Swift as

 func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! 

(with lowercase "v" in Value: , but none of

 func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! { } func getAxisLabel(axis: AnyObject!, Value: CGFloat) -> String! { } 

accepted by the compiler to satisfy protocol requirements.

As a workaround, you can annotate a method with an explicit Objective-C selector name:

 class ViewController: UIViewController, MyProtocol { @objc(getAxisLabel:Value:) func getAxisLabel(axis: AnyObject!, value: CGFloat) -> String! { return "" } } 
+9
source

Source: https://habr.com/ru/post/989923/


All Articles