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?
CodePudding user response:
Rather than introducing a killTask
property, you can save the Task
which you can later cancel
.
So you would have a property:
var task: Task<Void, Error>?
and
task = Task {
for z in arrayData {
try Task.checkCancellation()
let x1 = try await self.longTask1(z.var1)
let x2 = try await self.longTask2(z.var2)
...
}
}
And later
task?.cancel()