Apologies if this has already been asked; I wasn't able to find anything.
Suppose I have a function which has to be synchronous—perhaps it's being called as a callback from a C API or something—but all of its actual logic is asynchronous, so it gets wrapped in a Task
:
func syncFunction(foo: SomeNonSendableType) {
Task {
await asyncFunction(foo)
}
}
With -warn-concurrency
on, this will raise a warning about the non-Sendable
foo
getting captured by a closure, as one would expect. However, in the case that due to the way the program logic is structured, it is impossible for foo
ever to be used anywhere other than being passed to this function, one time, is there an escape hatch to promise this to the compiler, à la withoutActuallyEscaping
for nonescaping closures? So far, all I've been able to figure is to wrap it in a local @unchecked
type:
func syncFunction(foo: SomeNonSendableType) {
struct FooWrapper: @unchecked Sendable {
let foo: SomeNonSendableType
}
let wrapper = FooWrapper(foo: foo)
Task {
await asyncFunction(wrapper.foo)
}
}
This seems rather cumbersome, however. Is there a cleaner way to do this?