简体   繁体   中英

loop through array with delay - Swift

Im trying to loop through an array, lighting up one color at a time, and once its finished looping through every item, calling another function to run. So far i have this:

//Delay function from http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861
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
            }
        }
    }
}

But at the moment, all it does is delay one second, then lighting up all the colors at once. What i need is to light up the color in sequential order, with a second delay between each. Thanks in advance!

不要执行延迟1,将var delayTime = 1放在循环上方,然后在循环中执行self.delay(delayTime++)

You could try one of two things:

One: Insert sleep(1) at the beginning of your iteration of gameOrder .

Two: Modify your delay function a bit

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM