Using sending
tells the compiler:
- This value will be consumed by a concurrent context (e.g., a task).
- It must not be accessed again from the current task.
- If it is accessed again (e.g., reused or mutated), the compiler will raise an error.
In the code below, it enforces running the operation once. Using it in the 2nd Task causes a compiler error.
/// Using `sending` with a function.
func run(operation: sending @escaping @isolated(any) () async throws -> Void) {
Task {
print("1st task")
try await operation()
}
// 2nd call to operation is not allowed
Task {
print("2nd task")
// try await operation() // compiler error when uncommented
}
}