在NSDictionary数组中搜索键值



你好,我有一个Array,它有nsdictionary。

1st object->["111":title of the video]
2nd object->["123":title of the other]
3rd object->["133":title of  another]

假设我想在这个Array中搜索123 Key并获得它的值。我该怎么做呢?请帮帮我。由于

var subCatTitles=[AnyObject]()
let dict=[catData![0]:catData![4]]
self.subCatTitles.append(dict)

如果你的意思是你有一个这样的数组:

var anArray: [NSDictionary] = [
    ["111": "title of the video"],
    ["123": "title of the other"],
    ["133": "title of another"]
]

if let result = anArray.flatMap({$0["123"]}).first {
    print(result) //->title of the other
} else {
    print("no result")
}

(我假设"复制时先取"策略)

但是我强烈怀疑这个数据结构是否真的适合你的目的

首先,dictionary不是一个数组....

import Foundation
// it is better to use native swift dictionary, i use NSDictionary as you request
var d: NSDictionary = ["111":"title of the video","123":"title of the other","133":"title of  another"]
if let value = d["123"] {
    print("value for key: 123 is", value)
} else {
    print("there is no value with key 123 in my dictionary")
}
// in case, you have an array of dictionaries
let arr = [["111":"title of the video"],["123":"title of the other"],["133":"title of  another"]]
let values = arr.flatMap { (d) -> String? in
    if let v = d["123"] {
        return v
    } else {
        return nil
    }
}
print(values) // ["title of the other"]

最新更新