Skip to content

[cxx-interop] Using a C++ enum in Swift, cannot be used in C++ anymore (bi-directional Swift <-> C++ code) #75330

Open
@mrousavy

Description

@mrousavy

Description

I'm creating a C++ class that has a Swift implementation.

Since Swift doesn't support inheriting from C++ classes (yet), I have to write the methods twice, and just add the Swift instance as a member to the C++ instance:

#include "MyLibrary-Swift.h"

// C++ enum
enum class SomeEnum {
  first,
  second
};

// C++ class that holds the Swift class
class SomethingCxx {
public:
  SomethingCxx(MyLibrary::SomethingSwift swiftPart): _swiftPart(swiftPart) { }

  SomeEnum getSomeEnum() { return _swiftPart.getSomeEnum(); }

private:
  MyLibrary::SomethingSwift _swiftPart;
};
public class SomethingSwift {
  public var someEnum: SomeEnum { get { return .first } }
}

The problem here now is that Swift depends on the C++ code (SomeEnum), and C++ depends on the Swift code (SomethingSwift) - so it is a cyclic include.

I tried separating this out into multiple files, but no luck - Swift generates a single C++ header (MyLibrary-Swift.h), and if at any point I try to depend on C++ <-> Swift, it breaks the build with errors like these:

- No member named 'getSomething' in 'MyLibrary::SomethingSwift'

If I just return an Int instead of SomeEnum it works fine, so it is definitely the SomeEnum part that breaks.

Reproduction

public class SomethingSwift {
  public var someEnum: SomeEnum { get { return .first } }
}

Expected behavior

I expect Swift to properly resolve the C++ types and break up cyclic includes by either forward declaring it or just splitting the headers.

Environment

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.c++ interopFeature: Interoperability with C++clang importerArea → compiler: The clang importercompilerThe Swift compiler itselfenumFeature → type declarations: Swift enumeration declarationsswift 5.10unexpected errorBug: Unexpected error

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions