在循环中使用Swift的async/await

8

我正在琢磨苹果在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() 运行完毕(可能在另一个线程上)。我的问题是:
  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.


1
关于你的第一个问题,“lines”返回一个“AsyncSequence”,因此你不能使用同步的“for”循环来遍历它。 - Cristik
1
+1 对于“假装是”的观点。完全同意。在正式发布之前,应该进一步简化它。 - JerseyDevel
1个回答

8
< p > await id 的意思是从 staticImageIDsURL.lines 中获取一个 id 元素本身就是一种异步操作。

for await id in staticImageIDsURL.lines

在进入循环体执行该迭代之前,此操作必须完成。您可以阅读AsyncSequence文档以了解更多信息,或观看WWDC 2021会议的Meet AsyncSequence视频。


每次迭代时,您都需要等待当前操作完成。

let thumbnail = await fetchThumbnail(for: id)

每次启动新的获取调用时,此行将暂停函数,因此这些缩略图调用保证按顺序完成。这些调用绝不会并行发生,第一个必须在第二个被启动之前完成。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接