Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 DispatchTime.now to expected value dispatch_time_t aka UInt64."

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

like image 757
owlswipe Avatar asked Jun 25 '16 17:06

owlswipe


People also ask

How do I add a delay in Swift?

To add a delay to your code we need to use GCD . GCD has a built in method called asyncAfter , which will allow us to run code after a given amount of time. In the above code, Before delay will be printed out first and after 2 seconds, Async after 2 seconds will be printed.

What is a task in Swift?

Tasks in Swift are part of the concurrency framework introduced at WWDC 2021. A task allows us to create a concurrent environment from a non-concurrent method, calling methods using async/await. When working with tasks for the first time, you might recognize familiarities between dispatch queues and tasks.


1 Answers

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

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.    // Code you want to be delayed } 

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.

like image 111
owlswipe Avatar answered Sep 28 '22 06:09

owlswipe