[英]Swift Dictionary Get Key for Values
我有一個字典定義為:
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"
func findKeyForValue(value: String, dictionary: [String: [String]]) ->String?
{
for (key, array) in dictionary
{
if (array.contains(value))
{
return key
}
}
return nil
}
調用上面的函數,它將返回一個可選的String?
let drinks = ["Soft Drinks": ["Cocoa-Cola", "Mountain Dew", "Sprite"],
"Juice" :["Orange", "Apple", "Grape"]]
print(self.findKeyForValue("Orange", dictionary: drinks))
此函數將僅返回已傳遞值的數組的第一個鍵。
在Swift 2.0中,您可以過濾字典,然后將結果映射到數組。
let keys = drinks.filter {
return $0.1.contains("Orange")
}.map {
return $0.0
}
結果將是一個String
對象數組,表示匹配的鍵。
枚舉所有字典條目並測試每個值列表中所需的值,並累積值所在的鍵。
例如,查找列表中包含所需值的所有飲品:
let drinks = [
"Soft Drinks": ["Orange", "Cocoa-Cola", "Mountain Dew", "Sprite"],
"Juice" :["Apple", "Grape"]
]
let value = "Orange"
var keys = [String]()
for (key, list) in drinks {
if (list.contains(value)) {
keys.append(key)
}
}
print("keys: \(keys)")
鍵:[“軟飲料”]
這是Swift 4中的一個簡單解決方案:
let transport = ["bus": "red", "car": "white", "TARDIS": "blue"]
let key = (transport.filter { $0.value == "blue" }).first?.key
{
print (key)
}
TARDIS
試試這個(快速):
(dic as NSDictionary).allKeysForObject(<#T##anObject: AnyObject##AnyObject#>)
它對我有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.