How to perform two asynchronous operations with async let for two different types? Swift

Is there a way to perform asynchronous operations with the async let syntax for two different types, so that both of those methods are run in parallel?

I’ve tried with the TaskGroup as well but can’t figure this out

    func getOptionsAndVariants() async {
        do {
            async let options: [ProductOption] = NetworkManager.sharedInstance.getProductOptions(
            async let variants: [ProductVariant] = NetworkManager.sharedInstance.getProductVariants(
            await try options, variants // Wrong syntax

>Solution :


await try options, variants // Wrong syntax


let result = (await options, await variants)

Or, if either of the things you are awaiting also requires try, put it before the respective await. For instance if both of them requires try, you would say

let result = (try await options, try await variants)

Now result is a tuple of two values representing the returned values — result.0 is the options value, and result.1 is the variants value.

And the important thing is that result has no value until both async let values have returned — in parallel.

Leave a Reply