此代码从预设颜色数组中选择随机颜色.我如何制作它,以便不会多次挑选相同的颜色?
var colorArray = [(UIColor.redColor(), "red"), (UIColor.greenColor(), "green"), (UIColor.blueColor(), "blue"), (UIColor.yellowColor(), "yellow"), (UIColor.orangeColor(), "orange"), (UIColor.lightGrayColor(), "grey")]
var random = { () -> Int in
return Int(arc4random_uniform(UInt32(colorArray.count)))
} // makes random number, you can make it more reusable
var (sourceColor, sourceName) = (colorArray[random()])
Run Code Online (Sandbox Code Playgroud)
创建索引数组.从数组中删除其中一个索引,然后使用它来获取颜色.
像这样的东西:
var colorArray = [
(UIColor.redColor(), "red"),
(UIColor.greenColor(), "green"),
(UIColor.blueColor(), "blue"),
(UIColor.yellowColor(), "yellow"),
(UIColor.orangeColor(), "orange"),
(UIColor.lightGrayColor(), "grey")]
var indexes = [Int]();
func randomItem() -> UIColor
{
if indexes.count == 0
{
print("Filling indexes array")
indexes = Array(0..< colorArray.count)
}
let randomIndex = Int(arc4random_uniform(UInt32(indexes.count)))
let anIndex = indexes.removeAtIndex(randomIndex)
return colorArray[anIndex].0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码创建了一个数组indexes.该函数randomItem查看是否indexes为空.如果是,则用索引值填充它,范围从0到colorArray.count - 1.
然后它在indexes数组中选择一个随机索引,删除数组中该索引处的值indexes,并使用它来从您的数组中获取并返回一个对象colorArray.(它不会从中移除对象colorArray.它使用间接,并从indicesArray中删除对象,indexArray最初包含您的每个条目的索引值colorArray.
上面的一个缺陷是,从indexArray中获取最后一项后,用一整套索引填充它,并且从新重新填充的数组中获得的下一种颜色可能与最后一种颜色相同拿到.
可以添加额外的逻辑来防止这种情况发生.