Skip to content

Instantly share code, notes, and snippets.

Last active February 3, 2023 02:22
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
A reimplementation of the basics of MainActor. Sample code for
import Dispatch
final actor MyMainActor {
// Don’t allow others to create instances
private init() {}
// Requirements from the implicit GlobalActor conformance
typealias ActorType = MyMainActor
static var shared: ActorType = MyMainActor()
static var sharedUnownedExecutor: UnownedSerialExecutor {
// Requirement from the implicit Actor conformance
nonisolated var unownedExecutor: UnownedSerialExecutor {
// Store main executor in a global to keep it alive
private let mainExecutor = MainExecutor()
final class MainExecutor: SerialExecutor {
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
func enqueue(_ job: UnownedJob) {
DispatchQueue.main.async {
job._runSynchronously(on: self.asUnownedSerialExecutor())
// MARK: - Usage example
import Foundation
actor SomeActor {
func f() async {
await mainA()
func mainA() {
@main struct Main {
static func main() async {
await SomeActor().f()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment