how to convert custom Objc struct to NSValue in Swift?

593 views Asked by At

I define a custom struct in Objc

typedef struct {

    int a; 

    int b; 

} MyStruct;

In Objc I can convert the struct to NSValue use

MyStruct struct = {0};
NSValue *value = [NSValue value:&struct withObjCType:@encode(MyStruct)];

But how can I do this in Swift?

1

There are 1 answers

0
Anatoli P On

Somewhere in your Objective-C code add a function like

const char * __nonnull getMyStructOCT() {
    return @encode(MyStruct);
}

and make it available to Swift code via a bridging header. Then in your Swift code you can do, for example, the following:

let myStructOCT = getMyStructOCT()  // can then reuse myStructOCT over and over
var s = MyStruct(a: 111, b: 222)
let v = NSValue(bytes: &s, objCType: myStructOCT)

If you want to retrieve the value:

var s1 = MyStruct()
v.getValue(&s1)  // s1 now has your value