2016-07-02 81 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"]