-1

G'day, I have to loop through an array of objects and perform an operation on each item where the result is returned asynchronously. I'm very new to async/await style of coding in Swift and could not figure out how to find an easier solution. Appreciate any help. Please find the sample code below. I tried surrounding it inside Task but it does not work due to compiler error.


func performOperation(ids: [UUID]) -> [TypeA] {

var output: [TypeA] = []

for id in ids { 
  Task {
    let results = await someAsyncFunction(id)
    output.append(contendsOf: results)  // Does not compile.
  }
}

return output

}

func someAsyncFunction(id: UUID) async -> [TypeA] {
 // third party framework function.
}


0

1 Answer 1

2

It is generally not recommended to wait for async task synchronously, so once there is an async callee in the call stack, you have to modify all the callers to become async, up until one that doesn't need to return a value depending on the async call.

func performOperation(ids: [UUID]) async -> [TypeA]  {  //make this async
    var output: [TypeA] = []
    for id in ids {
        let results = await someAsyncFunction(id)
        output.append(contentsOf: results)
    }
    return output
}

func main(){
    Task{
        let output = performOperation(ids: ids)
    }
}

Sign up to request clarification or add additional context in comments.

3 Comments

This isn’t quite the same, because the items are all computed serially
Though OP doesn't mention whether serial or parallel is preferred. If parallel is preferred, check out taskGroup.waitForAll() in this post: stackoverflow.com/questions/76781545/…
Thank you both and the moderator that pointed me in the right direction towards TaskGroups. That's exactly what I have been looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.