-2

The following code doesn't print hello after the delay.

Anything wrong ?

 func delay(seconds delay:Int, closure:@escaping ()->()) {

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(delay)) {
        closure()
    }
}

delay(seconds: 5) { 
    print("hello")
}
Hamish
  • 78,605
  • 19
  • 187
  • 280
  • I would try to do it in Xcode, instead of playground. Also, print something in between the lines, to investigate what parts of the functions are running. Besides, Xcode is a little better in telling you what's happening,as opposed to playground. – Farini May 22 '17 at 16:08
  • 2
    Possible duplicate of [How do I run Asynchronous callbacks in Playground](https://stackoverflow.com/questions/24058336/how-do-i-run-asynchronous-callbacks-in-playground) – Hamish May 22 '17 at 16:18

2 Answers2

0

I got it working by creating a runloop, otherwise the program just exit without calling the asynchronous block. You shouldn't need this if you are developing for iOS app.

var keepAlive = true

   func delay(seconds delay:Int, closure:@escaping ()->()) {

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(delay)) {
        closure()
        }
    }


   delay(seconds: 5) { 
        print("hello")
        keepAlive = false
    }

let runLoop = RunLoop.current
while keepAlive && runLoop.run(mode: .defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.1)) {}
-2
let delayInSeconds = 5.0

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {

print("hello")

}
Alwin
  • 1,476
  • 3
  • 19
  • 35