gpt4 book ai didi

ios - Swift 字典获取值的键

转载 作者:搜寻专家 更新时间:2023-10-30 21:48:42 26 4
gpt4 key购买 nike

我有一个字典定义为:

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

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

如何获取给定值的 key 。

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
}

调用上面的函数会返回一个可选的字符串?

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

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

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

关于ios - Swift 字典获取值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32692450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com