Environment: Swift 5, Xcode 14, iOS 15, UIKit (NOT SwiftUI)
I have a long-running async task which I execute in a Task block:
Task { () -> () in
do {
for z in arrayData{
if killTask { // an external property
try Task.cancel() // **Swift Errors here**
}
let x1 = try await self.longTask1(z.var1)
let x2 = try await self.longTask2(z.var2)
etc.
}
} catch { print("Bad") }
} // end task
This fails with Swift syntax errors that Success and Failure in the Task can not be inferred. The Task produces no Result type. Can someone please point me in the correct direction by which I can cancel a task (with no input/output/Result types) by an external semaphore condition?
2
Answers
Rather than introducing a
killTask
property, you can save theTask
which you can latercancel
.So you would have a property:
and
And later
If you are spawning multiple unstructured tasks, for managing them and handling their cancellation, you can use
TaskGroup
andwithTaskCancellationHandler
to make your own cancellation handling construct similar to CoroutineScope in Kotlin and CancellationToken in C#. I have written about this in more detail here.