Skip to content

Commit fe0889b

Browse files
committed
[Concurrency] Offer way to get SerialExecutor from Actor
1 parent 25413d2 commit fe0889b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

stdlib/public/Concurrency/Executor.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,31 @@ public protocol SchedulableExecutor: Executor {
9393

9494
}
9595

96+
extension Actor {
97+
98+
/// Perform an operation with the actor's ``SerialExecutor``.
99+
///
100+
/// This converts the actor's ``Actor/unownedExecutor`` to a ``SerialExecutor`` while
101+
/// retaining the actor for the duration of the operation. This is to ensure the lifetime
102+
/// of the executor while performing the operation.
103+
@_alwaysEmitIntoClient
104+
@available(SwiftStdlib 5.1, *)
105+
public nonisolated func withSerialExecutor<T>(_ operation: (any SerialExecutor) throws -> T) rethrows -> T {
106+
try operation(unsafe unsafeBitCast(self.unownedExecutor, to: (any SerialExecutor).self))
107+
}
108+
109+
/// Perform an operation with the actor's ``SerialExecutor``.
110+
///
111+
/// This converts the actor's ``Actor/unownedExecutor`` to a ``SerialExecutor`` while
112+
/// retaining the actor for the duration of the operation. This is to ensure the lifetime
113+
/// of the executor while performing the operation.
114+
@_alwaysEmitIntoClient
115+
@available(SwiftStdlib 5.1, *)
116+
public nonisolated func withSerialExecutor<T>(_ operation: (any SerialExecutor) async throws -> T) async rethrows -> T {
117+
try await operation(unsafe unsafeBitCast(self.unownedExecutor, to: (any SerialExecutor).self))
118+
}
119+
}
120+
96121
extension Executor {
97122
/// Return this executable as a SchedulableExecutor, or nil if that is
98123
/// unsupported.

0 commit comments

Comments
 (0)