Swiftly

Swift 5.7 references for busy coders

isMainThread

isMainThread (part of Foundation) can be used to check to see if the current Thread is the main thread.

Simple example

import Foundation

print(Thread.isMainThread)

// Output: true

Example with Dispatch

import Foundation

print(Thread.isMainThread) // true

DispatchQueue.global(qos: .background).async {
  print(Thread.isMainThread) // false

  DispatchQueue.main.async {
    print(Thread.isMainThread) // true
  }
}

Example with @MainActor function and Dispatch

import Foundation
import _Concurrency // If using Playgrounds

func someFunction() {
  print("1️⃣ On main thread: \(Thread.isMainThread)")
}

@MainActor
func someOtherFunction() {
  print("2️⃣ On main thread: \(Thread.isMainThread)")
}

DispatchQueue.global(qos: .background).async {
  Task {
    someFunction()
    await someOtherFunction()
  }
}

// Output:
// 1️⃣ On main thread: false
// 2️⃣ On main thread: true

See also

Further reading