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:
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 { }
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.
lines
returns anAsyncSequence
, so you cannot use a synchronousfor
loop to iterate over it. – Bellman