Skip to content

Instantly share code, notes, and snippets.

@jacobsapps
Created April 30, 2025 21:32
Show Gist options
  • Save jacobsapps/650a3888656ae4351f884843f2b1f207 to your computer and use it in GitHub Desktop.
Save jacobsapps/650a3888656ae4351f884843f2b1f207 to your computer and use it in GitHub Desktop.
extension MainActor {
public static func assumeIsolated<T : Sendable>(
_ operation: @MainActor () throws -> T,
file: StaticString = #fileID, line: UInt = #line
) rethrows -> T {
typealias YesActor = @MainActor () throws -> T
typealias NoActor = () throws -> T
let executor: Builtin.Executor = unsafe Self.shared.unownedExecutor.executor
guard _taskIsCurrentExecutor(executor) else {
#if !$Embedded
fatalError("Incorrect actor executor assumption; Expected same executor as \(self).", file: file, line: line)
#else
Builtin.int_trap()
#endif
}
// To do the unsafe cast, we have to pretend it's @escaping.
return try withoutActuallyEscaping(operation) {
(_ fn: @escaping YesActor) throws -> T in
let rawFn = unsafe unsafeBitCast(fn, to: NoActor.self)
return try rawFn()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment