What's the type of any Task?

Let's say I want to record an arbitrary Task in a variable so that I can cancel it later. What should the type of this variable be?

var task: Task<Any, Never>

let foo = Task {

return "Hello World!"

}

let bar = Task {

return 42

}

task = foo // Cannot assign value of type 'Task<String, Never>' to type 'Task<Any, Never>'

1 Like

Existentials to the rescue.

protocol Cancellable {
    func cancel()
}

extension Task: Cancellable {}

var task: Cancellable!

let foo = Task {
    "Hello World!"
}

let bar = Task {
    42
}

task = foo
task.cancel()
8 Likes

That's a solution to this particular problem. Thanks.