Swift async/await in for loop
Asked Answered
J

1

10

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.

Jonquil answered 27/6, 2021 at 8:59 Comment(2)
Regarding your first question, lines returns an AsyncSequence, so you cannot use a synchronous for loop to iterate over it.Bellman
+1 for: “as is pretended to be”. Completely agreed. It should be streamlined quite a bit more before full release.Grandfatherly
E
10

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.

Exsanguine answered 27/6, 2021 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.