I'm trying to create a detached task that can throw an error. Here's a synthesized example of what I have.
@MainActor
var eventHandlerTask: Task<(), Never>? = nil
func eventsHandler(events: [BEIEvent]) async throws {
eventHandlerTask = Task.detached { [weak self] in
throw NSError()
}
}
Xcode complains with: Invalid conversion from throwing function of type '@Sendable () throws -> Bool' to non-throwing function type '@Sendable () async -> Bool'
How can I setup a detached task that throws?
CodePudding user response:
You have defined eventHandlerTask
to have a Failure
type of Never
. So it cannot throw an error.
However, if you change Never
to Error
, then it can take a closure that throws errors:
var eventHandlerTask: Task<(), Error>?