Skip to content

Instantly share code, notes, and snippets.

@dterekhov
Created October 23, 2025 09:27
Show Gist options
  • Select an option

  • Save dterekhov/dbd9338e3aa103b5020323d84ea9a3f0 to your computer and use it in GitHub Desktop.

Select an option

Save dterekhov/dbd9338e3aa103b5020323d84ea9a3f0 to your computer and use it in GitHub Desktop.
Compact async sequence demo showing outputs for all main transformation methods (map, filter, reduce, etc.) #swift-concurrency
import Foundation
// Helper async sequence emitting numbers 1...5
let numbers = [1, 2, 3, 4, 5].async
@main
struct Demo {
static func main() async {
print("map:", await numbers.map { $0 * 2 }.reduce([], +)) // [2, 4, 6, 8, 10]
print("filter:", await numbers.filter { $0.isMultiple(of: 2) }.reduce([], +)) // [2, 4]
print("contains:", await numbers.contains(3)) // true
print("allSatisfy:", await numbers.allSatisfy { $0 < 10 }) // true
print("max:", await numbers.max() ?? 0) // 5
print("min(by:):", await numbers.min(by: <) ?? 0) // 1
print("dropFirst:", await numbers.dropFirst(2).reduce([], +)) // [3, 4, 5]
print("flatMap:", await numbers.flatMap { [$0, $0] }.reduce([], +)) // [1,1,2,2,3,3,4,4,5,5]
print("compactMap:", await numbers.compactMap { $0.isMultiple(of: 2) ? $0 : nil }.reduce([], +)) // [2, 4]
print("zip:", await zip(numbers, numbers).map { $0 + $1 }.reduce([], +)) // [2, 4, 6, 8, 10]
print("prefix(while:):", await numbers.prefix(while: { $0 < 4 }).reduce([], +)) // [1, 2, 3]
print("reduce:", await numbers.reduce(0, +)) // 15
print("joined:", await [[1, 2], [3, 4]].async.joined().reduce([], +)) // [1, 2, 3, 4]
}
}
@dterekhov
Copy link
Author

669D6090-D1A9-43AC-9488-605600DD3A12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment