
Meet Swift Async Algorithms

Swift Async Algorithmsとは?
Appleが2022/03/24に発表したオープンソースのパッケージで、AsyncSequenceやConcurrencyを含んだもの
クロスプラットフォーム対応で、Swift Package Managerから導入できる
AsyncSequenceとは?
asynchronousとsequence両方の性質を持つプロトコル
asynchronous:非同期処理
sequence
ArrayやDictionaryなどが適合しているプロトコル
mapやfilterなどのインターフェイスを提供
Iteratorを利用してfor inループから値を取り出せる
つまりAsyncSequenceは
// 非同期で値が決まるものでもfor inループを適用できる
for await i in Counter(howHigh: 10) {
print(i, terminator: " ")
}
// Prints: 1 2 3 4 5 6 7 8 9 10
// Sequenceと同様にmapなどの高級関数が使える
let stream = Counter(howHigh: 10)
.map { $0 % 2 == 0 ? "Even" : "Odd" }
for await s in stream {
print(s, terminator: " ")
}
// Prints: Odd Even Odd Even Odd Even Odd Even Odd Even