Run blocks of code after a delay using Swift

Want to delay, the edge? OK

Image for post
Image for post
Photo by Jonathan Dubon on Unsplash

If you want to run a block of code after a delay, you’re in the right place.

Read on for the lowdown!

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to use Swift’s Playgrounds (guide HERE)

Terminology

Asynchronous: Work that can be run out of order, and usually have a callback when completed

Grand Central Dispatch (GCD): a low-level API for managing concurrent operations

WARNING:

If you are running this in Playgrounds you will need the following statement additionally in your code:

import PlaygroundSupportPlaygroundPage.current.needsIndefiniteExecution = true

Now PlaygroundSupport allows you to use various features of Playgrounds and is a rather excellent tool to use.

To help us run the Playground even though the function is Asynchronous. Excellent.

Running code after a delay

The code below will run after a three second delay.

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.0 ) {
print("This runs after the delay")
}

A alternative to do this is to extract the amount of time away from the

let time = 5.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
print("This runs after five seconds")
}

Now remember if you are running this in a Playground you will need to have the following (complete) code:

Whereas the code that we can run from a normal single view Xcode project would be:

Conclusion:

Delaying the execution of code is a simple function that most programming languages support.

In Swift, we simply have to use Grand Central dispatch to be able to achieve this.

Extend your knowledge

  • Async after has documentation by Apple (HERE)

The Twitter contact:

Any questions? You can get in touch with me here

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store