John Doe
John Doe

Reputation: 189

How to import Swift protocol in Objective-C

In my swift class I have the next protocol:

@objc
public protocol MyDelegate: AnyObject { ... }

And I need to access that protocol from the header file, not .m file. How can I do this?

I found few cases in SO and I tried them as

#import <ModuleName/ModuleName-Swift.h>

and

@import MySwiftClass;

but I still cannot use that protocol in my .h file in Obj-C. How can I fix this?

Upvotes: 2

Views: 1172

Answers (1)

mag_zbc
mag_zbc

Reputation: 6992

Refering to a Swift class or protocol from a generated header in a .h file would create a cyclical reference, therefore it is not possible. Apple suggest using a forward declaration and doing actual import in a .m file.

Source

When declarations in an Objective-C header file refer to a Swift class or protocol that comes from the same target, importing the generated header creates a cyclical reference. To avoid this, use a forward declaration of the Swift class or protocol to reference it in an Objective-C interface.

In other words, what you want is (at least currently) not possible.

Upvotes: 5

Related Questions