0
0
iOS Swiftmobile~5 mins

Async sequences in iOS Swift

Choose your learning style9 modes available
Introduction

Async sequences let your app handle data that comes over time without freezing the screen. They help you work with streams of values that arrive one by one.

Loading messages in a chat app as they arrive
Fetching live sensor data continuously
Downloading parts of a file step by step
Receiving updates from a server in real time
Syntax
iOS Swift
for await item in asyncSequence {
    // use item here
}

You use for await to loop over values that come asynchronously.

The asyncSequence can be any source that sends values over time.

Examples
This example creates a simple async sequence of numbers 1 and 2, then prints them.
iOS Swift
let numbers = AsyncStream<Int> { continuation in
    continuation.yield(1)
    continuation.yield(2)
    continuation.finish()
}

for await number in numbers {
    print(number)
}
This function returns an async sequence counting down from 3 to 1.
iOS Swift
func countdown() -> AsyncStream<Int> {
    AsyncStream { continuation in
        for i in (1...3).reversed() {
            continuation.yield(i)
        }
        continuation.finish()
    }
}

for await count in countdown() {
    print(count)
}
Sample App

This SwiftUI app shows a list of messages that appear one by one after pressing the button. It uses an async sequence to simulate receiving messages over time.

iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var messages: [String] = []

    var body: some View {
        VStack {
            List(messages, id: \.self) { message in
                Text(message)
            }
            Button("Start Receiving") {
                Task {
                    await receiveMessages()
                }
            }
        }
        .padding()
    }

    func receiveMessages() async {
        let messageStream = AsyncStream<String> { continuation in
            DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
                continuation.yield("Hello")
            }
            DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
                continuation.yield("How are you?")
            }
            DispatchQueue.global().asyncAfter(deadline: .now() + 3) {
                continuation.yield("Goodbye!")
                continuation.finish()
            }
        }

        for await message in messageStream {
            messages.append(message)
        }
    }
}
OutputSuccess
Important Notes

Async sequences help keep your app responsive by not blocking the main thread.

Use Task to start async work from UI events like button taps.

Remember to call continuation.finish() to end the sequence.

Summary

Async sequences let you handle data that arrives over time smoothly.

Use for await to loop through async sequences.

They are great for live updates, streams, and continuous data.