swift2 Swift字典获取值的关键字

5jdjgkvh  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(166)

我有一本字典定义为:

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

plicqrtu1#

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

此函数将只返回数组中传递了值的第一个键。

mnowg1ta

mnowg1ta2#

在Swift 2.0中,您可以过滤字典,然后将结果Map到数组。

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

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

2ledvvac

2ledvvac3#

枚举所有字典条目,测试每个值列表中所需的值,并累积该值所在的键。
例如,在列表中查找包含所需值的所有饮料:

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

键:[“软饮料”]

xkftehaa

xkftehaa4#

这是Swift 4中的一个简单解决方案:

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

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

塔迪斯

sirbozc5

sirbozc55#

试试这个(swift):

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

对我有用

相关问题