Swiftly

Swift references for busy coders

isMainThread

isMainThread (part of Foundation) can be used to check to see if the current Thread is the main thread. In modern Swift concurrency code, prefer @MainActor isolation, which lets the compiler guarantee main-thread execution instead of checking for it at runtime (MainActor.assertIsolated() is available for runtime assertions).

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

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