Consider a C++ method that retrieve struct of native typed arguments like enum class, sub-structs, std::string, int, etc...
I'd like to create a swift API that return the same struct but in swift variables
for example :
class ErrorMessage {
public:
int status;
std::string message;
};
class serverResponse {
public:
ErrorMessage error;
std::string str_value;
std::uint16_t int_val;
std::time_t last_seen;
EnumVal status;
};
serverResponse getServerResponse();
So I'd like to convert it to the swift equivalent struct with native members
open class serverResponseSwift : NSObject {
open class var error: ErrorMessage { get }
open var str_value: String { get }
open var int_val: UInt16 { get }
open var status: EnumVal { get }
};
I know that direct conversion is not yet possible so I need to use objective-C++ code as a mediator. So I've used a bridging header to include the converting method in objective-C++ which will look like this :
@interface Converter
- (serverResponseSwift) getServerStatusSwift;
@end
and the equivalent .mm file will implement the conversion function, but can I use the swift Class in objective-c in order to fill it up according to the CPP serverResponse
?
@implementation Converter
- (serverResponseSwift) getServerStatusSwift {
serverResponse x = getServerResponse();
/// How do I create serverResponseSwift out of serverResponse
}
Thanks !
can I use the swift Class in objective-c in order to fill it up according to the CPP
serverResponse
?
You can make your class Objective-C compatible by adding @objc
:
@objc
@objcMembers
open class ServerResponseSwift : NSObject {
open var error: ErrorMessageSwift
open var strValue: String
open var intVal: UInt16
//open var status: EnumValSwift
init(error: ErrorMessageSwift,
strValue: String,
intVal: UInt16
) {
self.error = error
self.strValue = strValue
self.intVal = intVal
//self.status = ...
}
}
And you can use it in your Objective-C++ code :
#import "SwiftAPICpp-Swift.h"
@implementation Converter
- (ServerResponseSwift *) getServerStatusSwift {
serverResponse x = getServerResponse();
//...
ServerResponseSwift *serverResponseSwift = [[ServerResponseSwift alloc] init...];
}
@end