簡體   English   中英

如何在 Swift 中將自定義 Objc 結構轉換為 NSValue?

[英]how to convert custom Objc struct to NSValue in Swift?

我在 Objc 中定義了一個自定義結構

typedef struct {

    int a; 

    int b; 

} MyStruct;

在 Objc 中,我可以將結構轉換為 NSValue 使用

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

但是我怎么能在 Swift 中做到這一點呢?

在 Objective-C 代碼的某處添加一個函數,如

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

並通過橋接頭使其可用於 Swift 代碼。 然后在您的 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)

如果要檢索值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM