我正在琢磨苹果在WWDC 2021上宣布的Swift 5.5中的新异步/等待模式,这似乎需要很多学习,并不像表面上看起来那么容易掌握。例如,在WWDC视频中,我刚刚看到了这个for循环:
for await id in staticImageIDsURL.lines {
let thumbnail = await fetchThumbnail(for: id)
collage.add(thumbnail)
}
let result = await collage.draw()
据我理解,每一次 for 循环 的迭代都会暂停该循环直到 fetchThumbnail() 运行完毕(可能在另一个线程上)。我的问题是:
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.