skip to Main Content

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


  1. 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()
    
    Login or Signup to reply.
  2. If you are spawning multiple unstructured tasks, for managing them and handling their cancellation, you can use TaskGroup and withTaskCancellationHandler 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search