Search code examples
swiftasync-awaittaskswift-concurrency

What is the correct way to await the completion of two Tasks in Swift 5.5 in a function that does not support concurrency?


I have an app that does some processing given a string, this is done in 2 Tasks. During this time i'm displaying an animation. When these Tasks complete i need to hide the animation. The below code works, but is not very nice to look at. I believe there is a better way to do this?

let firTask = Task {
    /* Slow-running code */
}

let airportTask = Task {
    /* Even more slow-running code */
}

Task {
    _ = await firTask.result
    _ = await airportTask.result
    
    self.isVerifyingRoute = false
}

Solution

  • I would make the tasks discardable with an extension. Perhaps something like this:

    extension Task {
        @discardableResult
        func finish() async -> Result<Success, Failure>  {
            await self.result
        }
    }
    

    Then you could change your loading task to:

    Task {
        defer { self.isVerifyingRoute = false }
        await firTask.finish()
        await airportTask.finish()
    }