Question
How to add static functions that use Tasks in Swift Task extensions
I'm curious if anyone has run into this question before. I initially ran into problems when trying to use an extension to Task
that calls Task.sleep
from a non-async function static function, then further digging has led me to this simpler discussion point.
This is valid Swift:
struct Foo {}
extension Foo {
static func bar() async throws {
}
static func bar() {
Task {
try await bar()
}
}
}
But the following is not:
extension Task {
static func bar() async throws {
}
static func bar() {
Task {
try await bar()
}
}
}
This gives me two errors (in Xcode 15.4):
Referencing initializer 'init(priority:operation:)' on 'Task' requires the types 'Failure' and 'any Error' be equivalent
'Cannot convert value of type '()' to closure result type 'Success'
.
Why is the compiler treating the Task
extension differently, and how do we solve this? I know that Success
and Failure
are two placeholder types for the Task generic, but I don't think they should be affecting the Task instance in the bar
static function's implementation.