ios – 从Swift数组中随机选择一个项目而不重复

此代码从预设颜色数组中选择随机颜色.我如何制作它,以便不会多次挑选相同的颜色?
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()])

解决方法

创建索引数组.从数组中删除其中一个索引,然后使用它来获取颜色.

像这样的东西:

var colorArray = [
  (UIColor.redColor(),"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;
}

上面的代码创建了一个数组索引.函数randomItem查看索引是否为空.如果是,则用索引值填充它,范围从0到colorArray.count – 1.

然后,它会在索引数组中选择一个随机索引,删除索引数组中该索引处的值,并使用它从colorArray中获取并返回一个对象. (它不会从colorArray中删除对象.它使用间接,并从indicesArray中删除对象,indexArray最初包含colorArray中每个条目的索引值.

上面的一个缺陷是,从indexArray中获取最后一项后,用一整套索引填充它,并且从新重新填充的数组中获得的下一种颜色可能与最后一种颜色相同得到.

可以添加额外的逻辑来防止这种情况发生.

以上是来客网为你收集整理的ios – 从Swift数组中随机选择一个项目而不重复全部内容,希望文章能够帮你解决ios – 从Swift数组中随机选择一个项目而不重复所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。