0

I have a list of objects and I'm currently looping over the list and executing a method for each of those objects like this:

var houses = [House]()
for house in houses {
    house.price = calculateHousePrice(house: house)
}
// continue here once all the prices have been calculated

Calculating the house price takes a long time, and is not dependent on the result of other calculations.

How can I use parallelism in Swift to speed this loop up? I've had a look at GCD, but I'm new to Swift and not sure what I should be using.

I've tried this:

for house in houses {
    DispatchQueue.global(qos: .background).async { [self] in
        house.price = calculateHousePrice(house: house)
    }
}
// continue here once all the prices have been calculated

but the loop completes before all the task have completed.

Changing async to sync helps, but I feel that I'm no better off than with the initial code.

4
  • 1
    This is a great use case for async/await with/without with TaskGroup Commented Jan 20, 2023 at 23:29
  • 1
    GCD is an intermediate layer of abstraction, above working with raw threads/locks, and below Tasks and TaskGroups in the new Swift Concurrency system. The way you're using it is totally find. "the loop completes before all the task have completed" Yep, that's to be expected. With GCD, your two options are to: 1) Use a DispatchGroup to wait until all the tasks finish (this is very bad, because it blocks the queue. Don't do it, I only mention it so I can tell you not to use it lol), 2) Use a dispatch queue to notify you when done, 3) Use a completion handler to be informed of when it's done Commented Jan 20, 2023 at 23:35
  • The modern Swift concurrency tools are probably the best suited for the job, and have by far the nicest ergonomics. Commented Jan 20, 2023 at 23:36
  • 1
    Does this answer your question? How to use Swift async/await in parallel Commented Jan 20, 2023 at 23:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.