2016-07-02 80 views
-1

你好,我有一个Array它有NSDictionaries。搜索NSDictionary数组中的键值swift

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

比方说,我想搜索在这个Array123重点,并得到了它的价值。我该怎么做? 请帮帮我。 感谢

UPDATE

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

可能的重复[搜索数组的字典的值在Swift](http://stackoverflow.com/questions/28203443/search-array-of-dictionaries-for-value-in-swift) – Cristik

回答

1

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

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") 
} 

(我假设“先取时重复”的策略。)

但是,如果这个数据结构,真正适合你的目的,我强烈怀疑。

+0

而不是'NSDictionary ',你可以使用'[[String:String]]'纯粹的快速:) –

0

起初,字典是不是数组....

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"]