检查字典中的数组并返回UIImage,但它返回两次相同的图像

时间:2015-11-12 07:58:22

标签: arrays xcode swift dictionary

我有一个字典示例: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数组返回给我的数组,如果它存在于我的字典中 到目前为止,我出来了这段代码

var images = [UIImage]()
for key in array {
if let image = dict[key] {
images.append(image!)
print("\(image!)")
print("\(images)")
}
}

我注意到当你打印图像时,控制台会告诉我:例如

[ <UIImage: A>, {480, 236}, <UIImage: A>, {480, 315}, <UIImage: B>, {480, 315}]

它打印两次A,A,B图像,但是当我打印图像时我只有A,B,C,你有解释吗? 请帮忙!

1 个答案:

答案 0 :(得分:1)

代码没有任何问题,我只是对此进行了测试并且有效:

let dict = ["A":UIImage(named: "A.png")!, "B":UIImage(named: "B.png")!, "C":UIImage(named: "C.png")!]
let keys = ["B", "C", "K", "A"]

var images = [UIImage]()
for key in keys {
    if let image = dict[key] {
        print(key)
        print(image)
        images.append(image)
    }
}

print(images)

for image in images {
    let v = UIImageView(image: image)
    v.frame.size = CGSize(10, 10)
    v.frame.origin.x = (self.view.subviews.last?.frame.origin.x ?? -10) + 10
    self.view.addSubview(v)
}

将您的问题标记为Off topic