Built-in AsyncSequences You Should Know

You don't always need to build custom AsyncSequences. Swift provides several built-in ones that cover common use cases.
Follow along with the code: iOS-Practice on GitHub
URL.lines
Read a file or URL line by line, asynchronously:
let url = URL(string: "https://example.com/data.txt")!
for try await line in url.lines {
print(line)
}
Perfect for processing large files without loading everything into memory.
FileHandle.bytes
Stream bytes from a file:
let handle = FileHandle(forReadingAtPath: "/path/to/file")!
for try await byte in handle.bytes {
process(byte)
}
NotificationCenter.notifications
Subscribe to notifications as an async sequence:
let notifications = NotificationCenter.default.notifications(
named: UIApplication.didBecomeActiveNotification
)
for await notification in notifications {
print("App became active: \(notification)")
}
This replaces the old addObserver pattern with clean async iteration.
URLSession.bytes
Stream download data as it arrives:
let (bytes, response) = try await URLSession.shared.bytes(from: url)
for try await byte in bytes {
// Process each byte as it downloads
}
Useful for progress tracking or processing large downloads.
AsyncStream Wrappers
Many APIs now offer async sequence versions:
// SwiftUI
AsyncStream(unfolding: { await nextFrame() })
// Combine bridge
publisher.values // AsyncSequence from any Publisher
Combining with Other Async Code
These integrate naturally with structured concurrency:
func processFile(at url: URL) async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
for try await line in url.lines {
group.addTask {
await process(line)
}
}
}
}
When to Use Each
| AsyncSequence | Use Case |
|---|---|
URL.lines | Text files, CSVs, logs |
FileHandle.bytes | Binary data, raw streams |
NotificationCenter.notifications | System events, custom notifications |
URLSession.bytes | Downloads with progress, streaming APIs |
Interview Tip
Knowing these built-in sequences shows practical experience. When asked about handling streaming data, mention URL.lines for text or URLSession.bytes for network data—it demonstrates you know the standard library.