简体   繁体   English

Swift Dictionary获取值的关键

[英]Swift Dictionary Get Key for Values

I have a dictionary defined as: 我有一个字典定义为:

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

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

How can I get the key, for a given value. 如何获取给定值的密钥。

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
}

Call the above function which will return an optional String? 调用上面的函数,它将返回一个可选的String?

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

print(self.findKeyForValue("Orange", dictionary: drinks))

This function will return only the first key of the array which has the value passed. 此函数将仅返回已传递值的数组的第一个键。

In Swift 2.0 you can filter the dictionary and then map the result to an array. 在Swift 2.0中,您可以过滤字典,然后将结果映射到数组。

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

The result will be an array of String object representing the matching keys. 结果将是一个String对象数组,表示匹配的键。

Enumerate through all the dictionary entries and test each value list for the value you want and accumulate the keys where the value is present. 枚举所有字典条目并测试每个值列表中所需的值,并累积值所在的键。

Example, finds all drinks that include the desired value in a list: 例如,查找列表中包含所需值的所有饮品:

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

keys: ["Soft Drinks"] 键:[“软饮料”]

This is an easy solution in Swift 4: 这是Swift 4中的一个简单解决方案:

let transport = ["bus": "red", "car": "white", "TARDIS": "blue"]

let key = (transport.filter { $0.value == "blue" }).first?.key
{
    print (key)
}

TARDIS TARDIS

try this (swift): 试试这个(快速):

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

it work for me 它对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM