How to prevent circular reference when Swift bridging header imports a file that imports Hopscotch-Swift.h itself

前端 未结 4 1832
栀梦
栀梦 2020-11-27 15:33

I am integrating Swift into a large existing Objective C project and have run into what I think is a circular reference.

The classes in question are as follows:

相关标签:
4条回答
  • 2020-11-27 16:06

    You could something like this in the .h file you suspect to trigger the circular reference:

    #ifndef MY_HEADER_H
    #define MY_HEADER_H
    your header file
    #endif
    
    0 讨论(0)
  • 2020-11-27 16:08

    The forward declaration by itself didn't work for me. It compiled without errors but still had warnings that the protocol couldn't be found. I treat all warnings as errors, so this isn't good enough.

    I was able to fix it by moving the protocol implementation into another category header.

    So here's what worked for me:

    In my MyOtherSwiftFile.swift:

    @objc protocol MyProtocol: class {
    func viewController(didFinishEditing viewController: MyViewController)
    }
    

    In my MyViewController.h:

    @interface MyViewController // Removed protocol implementation declaration here
    @end
    

    Added MyViewController+MyProtocol.h to project, and put this in there:

    @interface MyViewController (MyProtocol) <MyProtocol>
    @end
    

    The methods themselves can stay where they are if you want.

    After you implement the above and compile, you'll get compiler warning(s) somewhere in your code that requires that MyViewController implements MyProtocol. In that file, you will #import "MyViewController+MyProtocol.h"

    0 讨论(0)
  • 2020-11-27 16:14

    I ran into this when trying to use Swift classes inside Objective-C protocols, where the protocol was also implemented by another Swift class. It reeked of circular references and I guessed that it might be a problem trying to circularly generate the bridging headers, rather than a 'normal' circular include problem.

    The solution, for me, was to just use forward declarations before the protocol declaration:-

    // don't include the MyProject-Swift.h header
    
    // forward declaration of Swift classes used
    @class SwiftClass;
    
    @protocol MyProtocol <NSObject>
    - (SwiftClass *)swiftClass;
    @end
    
    0 讨论(0)
  • 2020-11-27 16:28

    Forward declaration should work, in your case.

    In your .h:

    @protocol MyProtocol;
    
    @interface MyController : UIViewController<MyProtocol>
    
    @end
    

    In your .m:

    #import "HopScotch-Swift.h"

    From How can I add forward class references used in the -Swift.h header? and the Swift interoperability guide:

    If you use your own Objective-C types in your Swift code, make sure to import the Objective-C headers for those types prior to importing the Swift generated header into the Objective-C .m file you want to access the Swift code from.

    0 讨论(0)
提交回复
热议问题