[Ios] Swift Dictionary获取关键值


Answers

在Swift 2.0中,你可以过滤字典,然后将结果映射到一个数组。

let keys = drinks.filter {
    return $0.1.contains("Orange")
}.map {
    return $0.0
}

结果将是表示匹配键的String对象的数组。

Question

我有一个字典定义为:

let drinks = [String:[String]]()

drinks = ["Soft Drinks": ["Cocoa-Cola", "Mountain Dew", "Sprite"], 
"Juice" :["Orange", "Apple", "Grape"]]

我怎样才能得到钥匙,给定的价值。

let key = (drinks as NSDictionary).allKeysForObject("Orange") as! String
print(key)
//Returns an empty Array. Should return "Juice"



试试这个(swift):

(dic as NSDictionary).allKeysForObject(<#T##anObject: AnyObject##AnyObject#>)

它为我工作