如何在 Swift 中将字典传递给 Objective-C 方法



我需要将字典传递给 Swift 中的 Objective-C 方法。在 Swift 中,代码是这样的:

let modelData: Dictionary<String, [Double]> = getModelData()
result = myChilitags.estimate3D(configAt: configFilePath, forModel: modelData);

(配置文件与此问题无关,只需忽略它即可。

我使用了一个.h文件:

@interface myChilitags : NSObject
+ (nonnull UIImage *)estimate3D:configAt:(NSString *)configFilePath forModel:(nonnull NSDictionary*) modelData;
@end

问题是我需要对 Objective-C 方法中的modelData做一些事情estimate3D但我不知道将字典值modelData传递给该方法后该怎么办。

我试图只打印模型数据值,但结果是:

1

我还尝试打印字典中的值,如下所示:

std::cout << modelData["face001"] << std::endl;

我很确定字典中有一个关键"face001",但结果仍然是:

1

我知道它一定与NSDictionary和Dictionary有关,但我只是不知道该怎么办。

首先,Swift 中的字典是结构的,NSDictionary 是类。
Objective-C 不是类型安全的,因此它不会显示错误。
如果你尝试在 Swift 中做同样的事情,它会告诉你
Cannot assign value of type '[String : [Double]]' to type 'NSDictionary'

let swiftDictionary = [String: [Double]]()
var nsDictionary = NSDictionary()
nsDictionary = swiftDictionary //shows error

所以你必须将 Swift 字典转换为 NSDictionary。

let modelData: Dictionary<String, [Double]> = getModelData()
let nsModelData = NSDictionary(dictionary: modelData)
result = myChilitags.estimate3D(configAt: configFilePath, forModel: nsModelData);

最新更新