我想知道是否可以使用Swift从使用数组作为键的字典中获取值。
例如,假设我想获得一种食物的形象,但只有食物的名称,如apple
。
var foodImages = [
["orange", "apple", "banana", "kiwi"] : UIImage(named: "fruit"),
["steak", "burger", "ground beef"] : UIImage(named: "beef"),
["carrots", "mushrooms", "potatoes"] : UIImage(named: "vegetable"),
]
如何使用该词典中的fruit
获取apple
的图片?
感谢任何帮助
答案 0 :(得分:0)
不,因为钥匙必须是可以清洗的。您必须将每个项目设为不同的密钥:
var dict = [(String,String):String]()
dict["apple"] = "fruit"
dict["banana"] = "fruit"
答案 1 :(得分:0)
嗯,你可以(如果它是NSArray
),但它不会有效......
基本的想法是filter
Dictionary
具有自定义过滤功能的键,它会检查每个键以查看它是contains
您要查找的项目。然后,由于filter
返回Array
,请取first
中的Array
项(如果存在)并使用 作为关键字从Dictionary
获取实际值。
最重要的是,Array
中Dictionary
作为关键字的唯一方法是NSArray
。由于它是NSArray
,因此您必须进行一些向下转换才能使事情正常进行。
它看起来像这样:
var foodImages = [
["orange", "apple", "banana", "kiwi"] : UIImage(named: "fruit"),
["steak", "burger", "ground beef"] : UIImage(named: "beef"),
["carrots", "mushrooms", "potatoes"] : UIImage(named: "vegetable"),
]
if let key = filter(foodImages.allKeys, { (list) -> Bool in
let foodList = list as [String]
return contains(foodList, "apple")
}).first as [String]? {
if let image = foodImages[key] as UIImage? {
/* use your image here */
}
}
您可以轻松地将其作为一项功能:
func getFoodImage(food: String) -> UIImage? {
if let key = filter(foodImages.allKeys, { (list) -> Bool in
let foodList = list as [String]
return contains(foodList, food)
}).first as [String]? {
if let image = foodImages[key] as UIImage? {
return image
}
}
return nil
}
let image = getFoodImage("apple")
话虽如此,使用NSArray
作为Dictionary
的关键词,你真的没有获得任何东西;只需将Array
中的每个项目添加为自己的密钥并将UIImage
存储为每个项目的值,就必须更好(并且效率更高)。由于UIImage
是一个类,因此您将存储对它的引用而不是副本,因此内存使用不存在问题。
var foodImages: [String: UIImage] = []
let fruitImage = UIImage(named: "fruit")
let beefImage = UIImage(named: "beef")
let vegetableImage = UIImage(named: "vegetable")
for food in ["orange", "apple", "banana", "kiwi"] {
foodImages[food] = fruitImage
}
for food in ["steak", "burger", "ground beef"] {
foodImages[food] = beefImage
}
for food in ["carrots", "mushrooms", "potatoes"] {
foodImages[food] = vegetableImage
}
然后它只是正常的Dictionary
下标访问:
let image = foodImages["apple"]
image
将为UIImage(named: "fruit")