I want to create an application according to MVVM model where my views are programmed in swiftui and my viewmodels are coded in C++. To do that i’ve done the following things:
-
Created a swift / swiftui ‘hello world’ application on my Mac Book Air M2 – MacOS Sonoma 14.6.1
-
Using xcode 15.4
-
Imported a C++ library in my application.
-
Changed the compiler setting for c++ interoperability (see picture).
-
Changed the searchpad for libraries (see picture).
-xcode compiler settings -
my c++ header looks like this:
//
// BartsCppLibrary.hpp
// BartsCppLibrary
//
// Created by BRS on 16/08/2024.
//
#ifndef CppLibrary_
#define CppLibrary_
/* The classes below are exported */
#pragma GCC visibility push(default)
#include <string>
class CppLibrary
{
public:
CppLibrary();
void IntPlus1(int32_t count);
std::string text;
};
#pragma GCC visibility pop
#endif
- my c++ class looks like this:
//
// BartsCppLibrary.cpp
// BartsCppLibrary
//
// Created by BRS on 16/08/2024.
//
#include <iostream>
#include "CppLibrary.hpp"
CppLibrary::CppLibrary()
{
text="";
}
void CppLibrary::IntPlus1(int32_t count)
{
text=std::to_string(count+1);
return;
};
- My module.map looks like this:
//
// module.modulemap
// BartsCppLibrary
//
// Created by BRS on 16/08/2024.
//
module BartsCppLibrary {
header "CppLibrary.hpp"
requires cplusplus
export BartsCppLibrary
}
- my swiftui conentview look like this:
//
// ContentView.swift
// Test
//
// Created by BRS on 11/08/2024.
//
import SwiftUI
import BartsCppLibrary
struct ContentView: View {
var body: some View {
@Observable var c = CppLibrary()
ZStack{
Rectangle()
.fill(Color("BackgroundColor"))
.frame (width : 300, height : 200)
.cornerRadius(20)
.shadow(radius: /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
VStack {
Text("BRS")
.font(.title)
Text ("Title")
.italic()
Spacer()
HStack{
Image(systemName: "envelope.fill")
Text("email")
}
HStack
{
Image(systemName: "link")
Text("link")
}
HStack
{
Image(systemName: "location.fill")
Text("Adress")
}
-->>ERROR-->> Text(c.text)
}.padding()
}.frame(width:300, height:200)
}
}
#Preview {
ContentView()
}
And produces an error on the Text(c.Text):
Error:
Initializer ‘init(_:)’ requires that ‘std.__1.string’ (aka ‘std.__1.basic_string<CChar, char_traits, allocator>’) conform to ‘StringProtocol’
I expected that you could use c++ code inside swiftui. Does any one know how to do this?
2