1

I have a class that is defined in Swift:

// SwiftClass.swift

@objc
class SwiftClass: NSObject {
  // ...
}

An Objective-C class can inherit from that Swift class:

// ObjCObject.h

#import "MyModule-Swift.h"

@interface ObjCObject: SwiftClass
  // ...
@end

However, when doing so, I cannot use that class in Swift code anymore.

To use it in Swift, I have to add it to the bridging header:

// MyModule-BridgingHeader.h

#import "ObjCObject.h"

as only classes referenced by the bridging header are visible to Swift code. And this creates a cyclic reference, as the bridging header must be processed prior to compiling the Swift source code yet the generated Swift header (MyModule-Swift.h) only exists after compiling the Swift source code and thus won't exist when the bridging header is being processed.

If it was just for method arguments, I could use forward declarations but an Obj-C class cannot inherit from a forward declared class.

So am I just missing something here or is it really the case that you can use Obj-C classes in Swift and Swift classes in Obj-C but you cannot use an Obj-C class in Swift if it inherits from a Swift class?

Mecki
  • 125,244
  • 33
  • 244
  • 253
  • if it's a protocol, just make a swift version of protocol with different/similar name. It is much better to make one way transfering not cross again and again. I mean if you want to use it swift finally, can you make subclass of Objc and then extend it with a swift protocol? – E.Coms Aug 30 '19 at 17:57
  • Duplicate of https://stackoverflow.com/questions/25670431/how-to-prevent-circular-reference-when-swift-bridging-header-imports-a-file-that ? – Martin R Aug 30 '19 at 18:09
  • Possible duplicate of [How to prevent circular reference when Swift bridging header imports a file that imports Hopscotch-Swift.h itself](https://stackoverflow.com/questions/25670431/how-to-prevent-circular-reference-when-swift-bridging-header-imports-a-file-that) – curiously77 Aug 30 '19 at 18:23
  • @MartinR You were correct, it was a duplicate but only when talking about protocols and the same problem arises when talking about inheritance. The given work around at the other question works for protocols but not for inheritance, so I changed that question to other case that bugs me, now it isn't a duplicate any longer. – Mecki Aug 30 '19 at 18:39

0 Answers0