2015-11-19 31 views
1

我正在做一個應用程序,它將很高興能夠比較一個數組/集合內的值。如何比較數組中的UIImages?

比方說,我有常量和數組像這樣:

let blueImage = UIImage(named: "blue") 
let redImage = UIImage(named: "red") 

button.setImage(blueImage, forState: .Normal) 
button2.setImage(redImage, forState: .Normal) 
button3.setImage(blueImage, forState: .Normal) 

var imageArray:Array<UIImage> = [button.currentImage, button2.currentImage, button3.currentImage] 

是否有那麼可以檢查/在我的數組比較值,並用藍色的更換紅色圖像。

更具體地是有辦法我可以檢查是否在陣列中的圖像的2/3包含特定的圖像(blueImage),然後替換的最後一個值(redImage)與(blueImage),使得所有具有相同的圖片。

回答

2

我想你可以沿着這些路線的東西了濾鏡陣列:

let filteredArray = filter(imageArray) { $0 == blueImage } 

,然後運行一個計數。

你也可以遍歷您的數組:

let countBlue = 0 

for i in 0..<imageArray.count { 

    if imageArray[i] == blueImage { 
     countBlue ++ 
    } 
} 

要更換一個元素:

imageArray[2] = blueImage 
+2

你是對的。 *但是... * filter(imageArray){$ 0 == blueImage}'適用於Swift 1.2(Xcode 6),您還應該提供Swift 2(Xcode 7)的示例:'imageArray.filter {$ 0 == blueImage} ':) – Moritz

+0

@Polis我不確定'{$ 0 == blueImage}'是做什麼的,你可以向我解釋一下嗎? – StevoHN

+0

@StevoHN'filter'在數組上迭代(就像循環一樣)並根據條件評估每個數組項。在這個閉包中,'$ 0'表示正在評估的* current *數組項目。 – Moritz