2

I keep running into an error telling me that Xcode failed to import bridging header. I notice this only happens when I import one specific class which imports my Swift header (ProjectName-swift.h).

Is it possible to import a class which imports the Swift header? If not, how do I use the class that imports the Swift header in my Swift classes while still being able to use the Swift code I need in the file?

Bill L
  • 2,576
  • 4
  • 28
  • 55

1 Answers1

10

Move the Swift header import from your class's header file to the implementation file for that class, and use @class to make a forward declaration of your Swift class.

For example, if you need to import the Swift header for a Swift class named MySwiftClass, then before your @interface in your header file, put the following line:

@class MySwiftClass;

That will allow your header to compile without importing the Swift header file directly. Your implementation will still need it, so that's why the import statement should be moved to the implementation file.

The same can be done if what you're trying to forward declare is a protocol. You just use the @protocol keyword.

Using forward declarations of classes or protocols is the Objective-C way to break circular dependencies even when only Objective-C code is being used. Sometimes it's even necessary to use a forward declaration for a class or protocol defined in the same header file if for example you have a protocol and class that both refer to each other.

Gavin
  • 8,204
  • 3
  • 32
  • 42
  • Your answer is 100% correct except for the bit about protocols I found. For anyone reading this, moving the import of the auto-generated Swift header to the .m works, and if you need to declare your class as adhering to a Swift protocol you need to mark it as adhering in the @interface line in your .m file as well. I checked and this will still return YES for conformsToProtocol, and will break the circular dependency. Thanks for helping guide me to the correct answer! – Bill L Apr 05 '16 at 19:14
  • 1
    @BillL Yes, you're right that you can mark a class as adhering to a protocol in the class extension in your .m file, that's definitely the best way to handle that. Especially if it's not necessary for other classes to know that your class conforms to that protocol, and is more just an implementation detail. But forward declarations of protocols are used in Objective-C header files often, specifically when a class has delegate and data source protocols defined. The `UITableView` header file has a forward declaration of `UITableViewDataSource`, for example. – Gavin Apr 05 '16 at 19:24
  • But what about `enum`s declared in Swift? :( – Rich Nov 17 '16 at 16:57