我有一个NSDictionary的数组,我希望用一个特定的键" id"从数组中获取一个字典。我尝试执行以下操作,但收到错误:
无法调用非功能类型的值#NSDictionary?'
考虑以下我想要做的例子:
let dictionaries: [NSDictionary] = [NSDictionary(dictionary: ["id": "123", "name": "the name"]),
NSDictionary(dictionary: ["id": "456", "name": "the other name"])]
if let dictionary = dictionaries.first(where: { $0.objectForKey("id") == "123" }) {
print(event.objectForKey("name") ?? "")
}
答案 0 :(得分:0)
您可以使用filter
:
let dictionaries: [NSDictionary] = [NSDictionary(dictionary: ["id": "123", "name": "the name"]),NSDictionary(dictionary: ["id": "456", "name": "the other name"])]
let requested = dictionaries.filter{ $0.object(forKey: "id") as? String == "123" }
first
。
let result = dictionaries.first(where: {$0.object(forKey: "id") as? String == "123"})
答案 1 :(得分:0)
问题是objectForKey
(Swift 3中object(for:)
)的结果。如果NSDictionary
没有类型,则结果为Any?
。您无法将Any?
与String
进行比较。然后需要转换为String
:
if let dictionary = dictionaries.first(where: { $0["id"] as? String == "123" }) {
print(dictionary["name"] ?? "")
}
但错误信息没有意义。
如果您使用Swift词典,甚至可以更好地将词典解析为结构/类,并且仅适用于您的类,则可以完全避免此问题。在解码/编码之外,切勿使用词典来表示应用中的对象。