【问题标题】:How to pass a Dictionary to Objective-C method in Swift如何在 Swift 中将字典传递给 Objective-C 方法
【发布时间】:2017-12-31 02:19:34
【问题描述】:

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

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

(configure文件与这个问题无关,忽略即可。)

我使用了.h 文件:

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

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

我试图只打印 modelData 值,但结果是:

1

我还尝试在 Dictionary 中打印值,例如:

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

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

1

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

【问题讨论】:

标签: ios objective-c swift dictionary


【解决方案1】:

首先,Swift 中的 Dictionary 是 struct,NSDictionary 是 class。
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);

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2016-02-28
    • 2012-12-11
    • 2016-09-20
    相关资源
    最近更新 更多