So far I am able to identify task using result value with tuples. Here is the sample
// Simulate Task A's work. It needs to check for cancellation.
func performTaskAWork() async -> (Bool,String) {
print(" Task A: Started.")
// Simulate work that takes longer
for i in 1...5 {
// --- Crucial Cancellation Check ---
// Option 1: Check the flag (allows cleanup)
if Task.isCancelled {
print(" Task A: Cancellation detected during iteration (i). Cleaning up...")
// Perform any necessary cleanup here
// You might return a specific value, throw, or just return early
return (false, "A (Cancelled)")
}
print("🟢 Task A: Working step \(i)/5...")
// Simulate work taking 1 second per step
try? await Task.sleep(for: .seconds(1))
}
print("✅ Task A: Finished naturally.")
return (false, "A (Completed)")
}
// Simulate Task B's work.
func performTaskBWork() async -> (Bool,String) {
print(" Task B: Started.")
// Simulate work that takes less time (for the cancellation scenario)
// Adjust sleep duration to test both scenarios (B finishes first vs. A finishes first)
let durationB = Int.random(in: 1...3) // B might finish before A (5s)
print(" Task B: Will take (durationB) seconds.")
try? await Task.sleep(for: .seconds(UInt64(durationB)))
print("✅ Task B: Finished.")
return (true, "B (Completed)")
}
// Main function to coordinate the tasks
func runTasksWithConditionalCancellation() async {
print(" Starting task coordination...")
await withTaskGroup(of: (Bool,String).self) { taskGroup in
taskGroup.addTask(operation: performTaskAWork)
taskGroup.addTask(operation: performTaskBWork)
for await (finished, string) in taskGroup {
if finished {
taskGroup.cancelAll()
}
print(string)
}
}
print("🏁 Task coordination finished.")
}
I want to identify tasks without using tuples or result value. Is there any other way?