Threading in Swift Simply Explained

Using Grand Central Dispatch (GCD) to speed up your app

Threading in iOS can be difficult to understand if you are coming from other platforms or are just a beginner at swift. Here’s a few tips to get you off on the right foot with Threading by using GCD.

First a precursor, threading is all about managing how work is prioritized in your app. Making your code execute faster is great, but what matters more how fast the user perceives your app to be.

Your goal as a developer is to prioritize anything that the user can see and interact with. It makes your app feel faster and snappier. Don’t make the user wait for something to load that they don’t notice or care about.

1. Only use the Main Thread for updating views

This is the easiest way to avoid issues. The basic idea is making sure that all views and interface elements are not blocked by other items in the Main Queue. A good example of this:

By only doing UI related work on the Main Thread you are ensuring that the user will not be blocked from loading a view or exiting a view. Avoid functions that have side effects that load data, image, etc on the Main Thread.

2. Know the different GCD Quality Of Service (QoS) types

There are a few different priorities to perform work in iOS. The higher qualities are prioritized first and are handled right away, whereas the lower qualities of service are handled when the system frees up some resources. Below is the different qualities ranked from highest to lowest.

Apple’s Documentation on different QoS

Creating your own queue with quality of service is really easy. You just have to give a label and a QoS.

3. Know what thread you are on

To know what the current thread is at any give spot in your code, Thread.current.

With this you can see exactly what priority the function is running on. You can also check if you are specifically on the main thread with Thread.current.isMainThread .

4. Almost always use async

This is one of the easiest way to make a mistake when threading, but is also easily avoidable. There are benefits to using sync in your code, and some special cases require it, but for someone just beginning iOS development probably better to just avoid it.

NEVER call sync on the Main DispatchQueue like such:

Also avoid using the sync on .userInteractive Queue because it is at the same priority level of the main queue.


Great articles on threading

  • Dive deeper with the WWDC Video on concurrency
  • If you are a visual learner read this post. It really helped me understand how the different Quality Of Service levels interact and how the different priorities are called.
  • Ray Wenderlich also has a great guide on threading