Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift:如何始终从洗牌数组中获得不同的值_Ios_Arrays_Swift_Shuffle - Fatal编程技术网

Ios Swift:如何始终从洗牌数组中获得不同的值

Ios Swift:如何始终从洗牌数组中获得不同的值,ios,arrays,swift,shuffle,Ios,Arrays,Swift,Shuffle,我基本上在一个按钮内创建了一个单词数组,每次按下按钮,我都会从数组中得到一个随机项。有时我会得到相同的东西。如果我不想我的物品重复,我总是想得到新的物品怎么办?很明显,我甚至想让他们在所有人都展示过一次之后重复他们的循环 @IBOutlet weak var shoppingLabel : UILabel! @IBAction func shoppingListButton(_ sender: Any) { var shoppingList = ["Oranges","Appl

我基本上在一个按钮内创建了一个单词数组,每次按下按钮,我都会从数组中得到一个随机项。有时我会得到相同的东西。如果我不想我的物品重复,我总是想得到新的物品怎么办?很明显,我甚至想让他们在所有人都展示过一次之后重复他们的循环

@IBOutlet weak var shoppingLabel : UILabel!
@IBAction func shoppingListButton(_ sender: Any) {
         var shoppingList = ["Oranges","Apples","Broccoli"].shuffled()
        print(shoppingList)
        resultLabel.text = shoppingList.first ?? ""
    }

这不是一个重复的问题,因为类似的问题在按钮外有一个数组,是一个var数组,我的是一个let。对于我的数组,我无法从中删除项目,因为它无法更改,而且不,我无法将其设置为var数组…

在随机数组中循环:

创建数组 洗牌一次 通过从开始到结束在数组中循环来拾取值 要实现1和2,只需将数组定义为常量,并将其移出要使用它的方法

要实现3,请创建一个附加变量来跟踪当前所在数组的索引,并在拾取值后将其递增

若要确保不超出数组的边界并实现数组的循环,请在索引大于数组的最后一个索引时将索引重置为0。一种简单的方法是在Swift中使用余数运算符%

例如

要从数组中随机选取非重复值,请执行以下操作:

创建数组 从数组中选择一个随机值 如果拾取的值等于最后一个值,请拾取一个新值 要实现2,请使用randomElement函数拾取随机元素。这比洗牌整个数组并每次拾取第一个元素的计算成本更低

要实现3,请使用while循环或类似方法,不断拾取随机元素,直到生成新元素

例如


您可能想对模的使用进行评论。我理解,但OP/未来的读者可能不会。我仍然会得到重复的值,如何更新标签?这种方法不应该产生重复的值,只有循环会重复。你是否也希望在周期之间消除随机性?是的,谢谢!但是我对标签也有一个问题:我应该给它什么命令才能让它显示始终不同的单词?resultLabel.text=shoppingList.first??现在它是这样的,但似乎不起作用好吧,检查我的更新答案的第二个例子,它应该做我理解你需要的。
let shoppingList = ["Oranges", "Apples", "Broccoli"].shuffled()
var currentIndex = 0

@IBAction func shoppingListButton(_ sender: Any) {

    // pick an item
    let nextItem = shoppingList[currentIndex]

    // update the label
    resultLabel.text = nextItem

    // increment the index to cycle through items
    currentIndex = (currentIndex + 1) % shoppingList.count
}
let shoppingList = ["Oranges", "Apples", "Broccoli"]

@IBAction func shoppingListButton(_ sender: Any) {

    // pick a random element that is not equal to the last one
    var nextItem: String?
    repeat {
        nextItem = shoppingList.randomElement()
    } while nextItem == resultLabel.text

    // update the label
    resultLabel.text = nextItem
}