[英]how to convert custom Objc struct to NSValue in Swift?
I define a custom struct in Objc我在 Objc 中定义了一个自定义结构
typedef struct {
int a;
int b;
} MyStruct;
In Objc I can convert the struct to NSValue use在 Objc 中,我可以将结构转换为 NSValue 使用
MyStruct struct = {0};
NSValue *value = [NSValue value:&struct withObjCType:@encode(MyStruct)];
But how can I do this in Swift?但是我怎么能在 Swift 中做到这一点呢?
Somewhere in your Objective-C code add a function like在 Objective-C 代码的某处添加一个函数,如
const char * __nonnull getMyStructOCT() {
return @encode(MyStruct);
}
and make it available to Swift code via a bridging header.并通过桥接头使其可用于 Swift 代码。 Then in your Swift code you can do, for example, the following:
然后在您的 Swift 代码中,您可以执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.