0

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?

desmond_yy
  • 83
  • 6
  • Possible duplicate of [Convert/Wrap Swift struct as NSValue for CAAnimation purposes?](https://stackoverflow.com/questions/32893429/convert-wrap-swift-struct-as-nsvalue-for-caanimation-purposes) – OykuNehir Nov 29 '19 at 13:31

1 Answers1

0

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
Anatoli P
  • 4,791
  • 1
  • 18
  • 22