Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift delay in loop

I have this delay function:

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

From here: dispatch_after - GCD in swift?

This code:

func start(){
   for index in 1...3 {
      delay(3.0){
         println(index)
      }
   }
}

After 3 sec, it gives:

3

3

3

My Goal:

After 3 sec: 1

After 6 sec: 2

After 9 sec: 3

How whould I achieve this? Thank You,

like image 287
Zoltan Avatar asked Apr 28 '16 14:04

Zoltan


2 Answers

try multiplying delay with index

func start(){
   for index in 1...3 {
      delay(3.0 * index){
         println(index)
      }
   }
}
like image 62
Shubhank Avatar answered Oct 13 '22 21:10

Shubhank


If you are (bizarrely) seeing 3 as the value of index that gets printed out on each of the iterations of the loop, you can do the following to ensure the correct (current) value of the iterator variable gets captured for the closure:

func start() {
    for index in 1...3 {
        let i = index
        delay(3.0 * i) {
            print(i)
        }
    }
}

I am not seeing that behaviour though with Xcode 7.3 & Swift 2.2 – the values printed are 1, 2, 3 with your version of the delay function. Are you perhaps using a very old version of Swift? This blog post actually covers the Swift for loop behaviour with value capture.

As noted in the other answer, multiplying the index with 3.0 accomplishes the 3,6,9 second delays.

like image 44
mz2 Avatar answered Oct 13 '22 22:10

mz2