John Ramos John Ramos - 1 year ago 586
iOS Question

How to program a delay in Swift 3

In earlier versions of Swift, one could create a delay with the following code:

let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
//put your code which should be executed with a delay here

But now, in Swift 3, XCode automatically changes 6 different things but then the following error appears: "Cannot convert
to expected value

How can one create a delay before running a sequence of code in Swift 3?

Answer Source

After a lot of research, I finally figured this one out.

let when = + 2 // change 2 to desired second delay.
DispatchQueue.main.after(when: when) {
// run your code with delay

This creates the desired effect in Swift 3.

Inspired by part of this answer.

Update for newest iteration of Swift 3:

let when = + seconds
DispatchQueue.main.asyncAfter(deadline: when){
   // Your code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download