Using Swift in a QT6 app

I simply opened arboreus_examples/qt6/CMake/UsingSwift/UsingSwift_v3/CMakeLists.txt in QT Creator and was able to build it and run.

In its main.cpp it creates a Swift wrapper and calls method:

ASwift* oSwift = new ASwift(&oEngine);
oSwift->mInit();
_A_DEBUG << oSwift->mString();

Its Swift code has some @objc attributes:

import Foundation

@objcMembers class ASwiftIOSSwift: NSObject {

	override init() {

		super.init();
		print("ASwiftIOSSwift init");
	}

	@objc func mString() -> NSString {

		let oString: NSString = "SwiftString";
		return oString;
	}
}

Yandex Mobile Ads also requires -objC flag:

Objective-C wrapper:

class ASwiftIOSNative : public QObject {

	Q_OBJECT

	public:

		explicit ASwiftIOSNative(QObject* parent = nullptr);
		virtual ~ASwiftIOSNative(void);

		QString mString(void);
};
// iOS Class header
#import "aswiftiosobjc.h"

// Global variables
static ASwiftIOSObjC* gSwiftIOSObjC __unused = nil;

// iOS Class
@implementation ASwiftIOSObjC


// ---------------------------------------
#pragma mark Init

+(ASwiftIOSObjC*) mInstance {

	static dispatch_once_t oPredicate;
	static ASwiftIOSObjC* oSharedDelegate = nil;
	dispatch_once(&oPredicate, ^{
		oSharedDelegate = [[super alloc] init];
		_A_DEBUG << "ASwiftIOSObjC instance created";
	});

	_A_DEBUG << "ASwiftIOSObjC instance shared";
	return oSharedDelegate;
}

-(instancetype) init {

	self = [super init];
	if (self) {
		
		[self setPSwift:[[ASwiftIOSSwift alloc] init]];
		_A_DEBUG << "ASwiftIOSObjC init";
		
	}
	return self;
}


@end


// -----------
// Qt part
// -----------

QT_BEGIN_NAMESPACE

// Class header
#include "aswiftiosnative.h"


// -----------
/*!
	\fn

	Doc.
*/

ASwiftIOSNative::ASwiftIOSNative(QObject* parent) : QObject(parent) {

	gSwiftIOSObjC = [ASwiftIOSObjC mInstance];

	_A_DEBUG << "ASwiftIOSNative created";
}


// -----------
/*!
	\fn

	Doc.
*/

ASwiftIOSNative::~ASwiftIOSNative(void) {

	_A_DEBUG << "ASwiftIOSNative deleted";
}


// -----------
/*!
	\fn

	Doc.
*/

QString ASwiftIOSNative::mString(void) {

	QString oString = QString::fromNSString([gSwiftIOSObjC.pSwift mString]);
	return oString;
}

QT_END_NAMESPACE

ASwift is a redundant C++ class that uses Objective-C object internally:

class ASwift : public QObject {

	Q_OBJECT

	public:

		explicit ASwift(QObject* parent = nullptr);
		virtual ~ASwift(void);

		void mInit(void);
		QString mString(void);

	private:

		ASwiftIOSNative* pIOSNative = nullptr;
};

It is not clear enough is it possible to make the following code work in a QT6 app:

1 Response to Using Swift in a QT6 app

  1. dmitriano says:

    CMake Examples for Swift
    https://github.com/compnerd/swift-cmake-examples
    Simple project with a library that depends on an external package which is built as part of the build

Leave a Reply

Your email address will not be published. Required fields are marked *