I'm trying to develop a mix-language (c++ and Swift) framework where calls are mainly from c++ -> Swift. However, I'm having problems with get Swift functions available in c++ when they take a c++ enum value as parameter.
Assume the following c++ header:
#pragma once
enum class MyCppEnumClass { A, B, C };
enum class MyCppEnum { D, E, F };
and following Swift source file:
public func swiftFunctionWithCppEnumClass(_ value: MyCppEnumClass) {
print("Swift function with C++ enum: \(value)")
}
public func swiftFunctionWithCppEnum(_ value: MyCppEnum) {
print("Swift function with C++ enum: \(value)")
}
The project compiles correctly this way, so the bridging of the enum types does work, making both the enum and enum class available in Swift. However, when inspecting the generated Swift header, I'm seeing this:
namespace CxxInteropExperiments SWIFT_PRIVATE_ATTR SWIFT_SYMBOL_MODULE("CxxInteropExperiments") {
// Unavailable in C++: Swift global function 'swiftFunctionWithCppEnum(_:)'.
// Unavailable in C++: Swift global function 'swiftFunctionWithCppEnumClass(_:)'.
} // namespace CxxInteropExperiments
I can't find any information on swift.org (https://www.swift.org/documentation/cxx-interop/) that this would be unsupported. Currently the only solution I can find is to 'mirror' the enum with native Swift enum and implement a convert function in c++ like so:
public enum MySwiftEnum {
case A
case B
case C
}
public func swiftFunctionWithSwiftEnum(_ value: MySwiftEnum) {
print("Swift function with Swift enum: \(value)")
}
#include <CxxInteropExperiments/CxxInteropExperiments-Swift.h>
CxxInteropExperiments::MySwiftEnum convert(MyCppEnumClass e) {
switch(e) {
case MyCppEnumClass::A: return CxxInteropExperiments::MySwiftEnum::A();
case MyCppEnumClass::B: return CxxInteropExperiments::MySwiftEnum::B();
case MyCppEnumClass::C: return CxxInteropExperiments::MySwiftEnum::C();
}
}
void callSwiftFunctionWithEnum(MyCppEnumClass e) {
CxxInteropExperiments::swiftFunctionWithSwiftEnum(convert(e));
}
and not use c++ enum or enum classes in Swift function signatures that I want to be able to use in c++.
Am I missing something obvious, or is passing c++ enum values directly to Swift functions just not possible? Any help is appreciated.