How can I use a Swift type inside a C++ class?

I have this Swift class:

public final class SwitcherGroup {
	var switchers: [Switcher]
	init(switchers: [Switcher] = []) {
		self.switchers = switchers
	}
	...
}

The Switcher type is declared in C++:

// Switcher.hpp
class Switcher {
	std::string ipAddress;
	std::string name;
	int programmeBus;
	int previewBus;
public:
	...
};

I want to store a SwitcherGroup reference in the Switcher class, so that every Switcher knows which group it's a part of (and can access properties and methods from its group). To achieve this, I first tried:

// Switcher.hpp
#import <ATEM-Swift.h> // The project name is "ATEM"
class Switcher {
	Switcher switcher;
	...
};

but I received the error ATEM-Swift.h not found. This StackOverflow comment suggests that Swift headers can't be imported into C++ header files, only in implementations, and this is consistent with the sample code I've found.

I'm new to C++, but my understanding is that type definitions go in header files, while compiled files are only for function/method implementations. If this is the case, and it's also the case that I can't access my Swift types from header files, how can I make a class with a property of a type from Swift? Am I thinking about it the wrong way?

That's usually true, but not always. You can have type definitions in the .cpp file if they are private and you don't want to share them with other modules (usually they are also wrapped into anonymous namespace to avoid conflicts at the link time). And you can have implementations of the inline and templated functions in the header.

In your case you probably need to create a forward declaration to refer to entities from ATEM-Swift.h without importing it.

Something like this:

// Switcher.hpp
class SwitcherGroup;

class Switcher {
    SwitcherGroup *_group; // Note: pointer, not object itself
};

// Switcher.cpp
#import "Switcher.hpp"
#import <ATEM-Swift.h>

...
1 Like