O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using asyncAfter

The asyncAfter function will execute a block of code asynchronously after a given delay. This is very useful when we need to pause the execution of our code. The following code sample shows how we would use the asyncAfter function:

let queue2 = DispatchQueue(label: "squeue.hoffman.jon") 
let delayInSeconds = 2.0 
let pTime = DispatchTime.now() + Double(Int64(delayInSeconds * 
Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) 
queue2.asyncAfter(deadline: pTime) { 
  print("Times Up") 
} 

In this code, we begin by creating a serial dispatch queue. We then create an instance of the DispatchTime type and calculate the time to execute the block of code based on the current time. We then use the asyncAfter function to execute the code block ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required