While it has not been officially proposed (reader: please do that if you're so inclined!), there has been talk on the Swift forums that only allowing for Task<Void, Never> to be "@discardableResult" would be a good enough solution to the problem.
As it is now, Task.init and Task.detached are always discardable. If they were not, the thinking goes, the "Result … is unused" message would cause the programmer to be aware that further action is warranted…
…e.g. by explicitly disregarding a result when the task's Success is not Void…
_ = Task { "🔮" }
…or by being nudged to store the task, and deal with the error later.
let task = // Task<Void, Error>
Task.detached {
try await myThrowingFunction()
runWhenSuccessful()
}
await task.value // Property access can throw but is not marked with 'try'
I support this proposed change. But it would still be possible, as it is now, to disregard a task that completed with an error, using an underscore, and I don't think that underscore represents intent very well:
_ = Task.detached {
try await myThrowingFunction()
runWhenSuccessful()
}
The only way to enforce handling of the error is to get the idea that the operation closure does not throw, into the type system, using an explicit Never.
invalid conversion from throwing function of type '@Sendable () async throws -> ()' to non-throwing function type '@Sendable () async -> ()'
Task<_, Never>.detached {
try await myThrowingFunction()
runWhenSuccessful()
}
do/catch:
Task<_, Never>.detached {
do {
try await myThrowingFunction()
runWhenSuccessful()
} catch { }
}
Explicit Error perhaps carries a better idea of intention than _ = Task:
Task<_, Error>.detached {
try await myThrowingFunction()
runWhenSuccessful()
}