我有一个字典示例: 1)
var dict = [["A":UIImage(named: "A.png"),"B":UIImage(named: "B.png"),"C":UIImage(named: "C.png")]

我有一个数组: 2)
var array = ["A", "C", "K", "B"]

我想在我的字典中检查这个数组,然后以相同的顺序将字典的UIImage数组返回给我的数组,如果它存在于我的字典中,当它找不到图像时将其放空/ p>
请帮忙!
答案 0 :(得分:2)
//迭代数组,并收集另一个数组中关联的图像。
var images = [UIImage]()
for key in array {
if let image = dict[key] {
images.append(image)
}
}
//图像现在将按照数组中指定的键的顺序包含图像。
修改强>:
如果你想要甚至nil项都在数组中,那么你需要有一个可选的图像对象数组。
var images = [UIImage?]()
for key in array {
images.append(dict[key])
}
//While fetching the items, ensure you unwrap them-
//for example- the following tries to fetch and unwrap images from this array
for image in images {
if let image = image {
//Do something with the image
}else {
//The image was not present.
}
}