如何按时间顺序遍历数组?

时间:2018-08-15 13:30:04

标签: arrays swift func

我正在开发一个拖放游戏,其中用户将标签移动到相应的节点。

我目前有以下代码:

func setupDragLabel(){
    let random = Int(arc4random_uniform(1))

    if random == 0 {
        let numbersArray = ["one", "two", "three", "four", "five"]
        let index = Int(arc4random_unifrom(UInt32(numbersArray.count)))
        label.text = numbersArray[index]
        label.name = "numbers"
        }
    else{
        let lettersArray = ["a", "b", "c", "d", "e"]
        let index = Int(arc4random_uniform(UInt32(lettersArray.count)))
        label.text = lettersArray[index]
        label.name = "letters"
    }
    ((self.addChild(label))
}

然后结束触摸:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if label.name == "numbers"{
        if numbersBin.frame.contains(label.position){
            label.removeFromParent()
            setupDragLabel()
        }
    }
    if label.name == "letters" {
        if lettersBin.frame.contains(label.position){
            label.removeFromParent()
            setupDragLabel)
        }
    }
}

此刻,该函数将永远运行,从数组中随机选择。但是,我想对其进行设置,以使功能setupDragLabel()在每个数组中移动,当到达两个数组的末尾时,它将移动到下一个屏幕。我将如何更改当前代码(我知道这意味着删除arc4random,但不确定如何在顶部修复该问题),以及我需要编写什么函数才能使其继续运行?

1 个答案:

答案 0 :(得分:0)

我建议设置numbersArraylettersArray变量,然后从这些数组中删除已经使用的元素。

var numbersArray = ["one", "two", "three", "four", "five"]
var lettersArray = ["a", "b", "c", "d", "e"]

func setupDragLabel(){
    let random = Int(arc4random_uniform(1))

    if random == 0, numbersArray.count > 0 {
        let index = Int(arc4random_uniform(UInt32(numbersArray.count)))
        label.text = numbersArray[index]
        numbersArray.remove(at: index)
        label.name = "numbers"
        self.addChild(label)
    }
    else if lettersArray.count > 0 {
        let index = Int(arc4random_uniform(UInt32(lettersArray.count)))
        label.text = lettersArray[index]
        label.name = "letters"
        self.addChild(label)
    }
}