Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Created March 28, 2025 22:47
Show Gist options
  • Save brennanMKE/7595e7879e7830a59d1590f7dffb9951 to your computer and use it in GitHub Desktop.
Save brennanMKE/7595e7879e7830a59d1590f7dffb9951 to your computer and use it in GitHub Desktop.
Swift with sending parameter

What sending enforces

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
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment