2025-02-07 17:40:07
,某些文章具有时效性,若有错误或已失效,请在下方留言。Swift provides several ways of receiving a potentially endless flow of data, allowing us to read values one by one, or loop over them using for
, while
, or similar.
Swift 提供了几种接收可能无穷无尽的数据流的方法,允许我们逐个读取值,或者使用 for
、while
或类似方法遍历它们。
The simplest is the Sequence
protocol, which continually returns values until the sequence is terminated by returning nil
. Lots of things conform to Sequence
, including arrays, strings, ranges, Data
, and more. Through protocol extensions Sequence
also gives us access to a variety of methods, including contains()
, filter()
, map()
, and others.
最简单的是 Sequence
协议,它会持续返回值,直到通过返回 nil
终止序列。很多东西都符合 Sequence
,包括数组、字符串、范围、Data
等等。通过协议扩展,Sequence
还允许我们访问各种方法,包括 contains()
、filter()
、map()
等。
The AsyncSequence
protocol is almost identical to Sequence
, with the important exception that each element in the sequence is returned asynchronously. I realize that sounds obvious, but it actually has two major impacts on the way they work.AsyncSequence
协议与 Sequence
几乎相同,但重要的例外是序列中的每个元素都是异步返回的。我知道这听起来很明显,但实际上它对他们的工作方式有两大影响。
First, reading a value from the async sequence must use await
so the sequence can suspend itself while reading its next value. This might be performing some complex work, for example, or perhaps fetching data from a server.
首先,从异步序列中读取值必须使用 await
,以便序列可以在读取其下一个值时挂起自身。例如,这可能是执行一些复杂的工作,或者可能是从服务器获取数据。
Second, more advanced async sequences known as async streams might generate values faster than you can read them, in which case you can either discard the extra values or buffer them to be read later on.
其次,更高级的异步序列(称为异步 流 )生成值的速度可能比您读取它们的速度更快,在这种情况下,您可以丢弃额外的值或缓冲它们以供稍后读取。
So, in the first case think of it like your code wanting values faster than the async sequence can make them, whereas in the second case it’s more like the async sequence generating data faster than than your code can read them.
因此,在第一种情况下,可以将其视为您的代码希望比异步序列更快地生成值,而在第二种情况下,它更像是异步序列生成数据的速度比您的代码读取数据的速度要快。
Otherwise, Sequence
and AsyncSequence
have lots in common: the code to create a custom one yourself is almost the same, both can throw errors if you want, both get access to common functionality such as map()
, filter()
, contains()
, and reduce()
, and you can also use break
or continue
to exit loops over either of them.
否则,Sequence
和 AsyncSequence
有很多共同点:自己创建自定义的代码几乎相同,如果需要,两者都可以抛出错误,都可以访问通用功能,如 map()
、filter()
、contains()
和 reduce(),
你也可以使用 break
或 continue
退出它们中的任何一个循环。