延迟遍历数组 - Swift

loop through array with delay - Swift

我试图遍历一个数组,一次点亮一种颜色,一旦完成遍历每个项目,调用另一个函数 运行。到目前为止我有这个:

//Delay function from 
func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

@IBAction func computerTurn(){
    if(isFirstLevel){levelLabel.text = ("Level 1"); isFirstLevel = false}
    else{ level++ }

    var gameOrderCopy = gameOrder
    var randomNumber = Int(arc4random_uniform(4))
    gameOrder.append(randomNumber)
    var i = 0

    for number in gameOrder{

        if number == 0{
            self.greenButton.highlighted = true
            self.delay(1){
                self.greenButton.highlighted = false
                }
        }

        else if number == 1{
            self.redButton.highlighted = true
            self.delay(1){
                self.redButton.highlighted = false
               }

        }

        else if number == 2{
            self.yellowButton.highlighted = true
            self.delay(1){
                self.yellowButton.highlighted = false
                }
        }
      else if number == 3{
        self.blueButton.highlighted = true
        self.delay(1){
            self.blueButton.highlighted = false
            }
        }
    }
}

但目前,它只是延迟一秒钟,然后立即点亮所有颜色。我需要的是按顺序点亮颜色,每个之间有第二次延迟。提前致谢!

您可以尝试以下两种方法之一:

一:在 gameOrder.

迭代的开头插入 sleep(1)

二:稍微修改一下你的delay功能

func delay(delay:UInt32, closure:()->()) {
        sleep(delay)
        closure()
    }

不做延迟1,把var delayTime = 1放在循环上面,在循环里做self.delay(delayTime++)