-1

When I use the dispatch_after method to produce a delay it never executes the code after it. I need to return an array but it always skips over it.

Here is matt's delay method:

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

Here is the method where the error occurs:

func rollDice() -> Array<Int> {
    var diceArray = [Int]()
    let timerTime:NSTimeInterval = 0.3
    delay(timerTime) {
        //my code
    }
    return diceArray //NEVER GETS HERE
}
Community
  • 1
  • 1
arocks124
  • 19
  • 6
  • 3
    Actually, that's _my_ `delay` method. http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861 – matt Mar 07 '16 at 01:21
  • @matt sorry for not crediting you. I edited it so it now links to your page. – arocks124 Mar 07 '16 at 01:34

1 Answers1

5

You don't seem to understand what a delay is. The code will operate in this order:

func rollDice() -> Array<Int> {
    var diceArray = [Int]() // ONE
    let timerTime:NSTimeInterval = 0.3
    delay(timerTime) {
        // THREE
    }
    return diceArray // TWO
}

So, your rollDice will return an empty diceArray before the code inside the delay ever runs. Whatever you are doing inside the delay is thus ineffective from that point of view; it has, and can have, no effect whatever on what rollDice returns.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • He could refactor his `rollDice()` method to take a completion handler (where he passes back the array). – Nicolas Miari Mar 07 '16 at 01:50
  • @NicolasMiari Absolutely. He could do a lot of things. But the question wasn't what to do (to gain some end - but what end? I'm not entirely sure what he's even _trying_ to do). The question was to explain the phenomenon of what's happening. – matt Mar 07 '16 at 02:26