Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift async/await in for loop

I am scratching my head on new async/await pattern in Swift 5.5 announced in WWDC 2021 and there seems to be lot of learning involved and not as easy to grasp as is pretended to be. I just saw this for loop for instance in WWDC video:

    for await id in staticImageIDsURL.lines {

        let thumbnail = await fetchThumbnail(for: id)
        collage.add(thumbnail)
    }

    let result = await collage.draw()

As I understand, every iteration of for loop will suspend the for loop till fetchThumbnail() finishes running (probably on a different thread). My questions:

  1. What is the objective of await id in the for loop line? What if we have the for loop written as following without await?

      for id in staticImageIDsURL.lines {
    
      }
    
  2. Does the for loop above always ensures that images are added to collage in sequential manner and not in random order depending on which thumbnails are fetched early? Because in classic completion handler way of writing code, ensuring sequential order in array requires some more logic to the code.

like image 243
Deepak Sharma Avatar asked Apr 27 '26 02:04

Deepak Sharma


1 Answers

The await id means geting an id element from the staticImageIDsURL.lines is an asynchronous operation in itself.

for await id in staticImageIDsURL.lines

This operation has to complete before we enter for loop's body for that iteration. You should read AsyncSequence docs to know more on this OR can watch Meet AsyncSequence WWDC 2021 session.


For each iteration, you are waiting for current operation to complete when you say this.

let thumbnail = await fetchThumbnail(for: id)

This line will suspend the function each time a new fetch call is initiated, so these thumbnails calls are guaranteed to be completed sequentially. These calls NEVER happen in parallel, first has to complete before second one is initiated.

like image 66
Tarun Tyagi Avatar answered May 04 '26 15:05

Tarun Tyagi