How do I bridge delegate callbacks to AsyncStream in Swift?

In Swift, you can bridge delegate callbacks to an `AsyncStream` to allow asynchronous handling of delegate methods. This can be particularly useful when dealing with UI updates or networking callbacks that follow a delegate pattern. Below is an example of how to implement this bridging.

import Foundation // Define a delegate protocol protocol SomeDelegate: AnyObject { func didReceiveData(_ data: Data) } // A class that follows the delegate pattern class DataSource { weak var delegate: SomeDelegate? func fetchData() { // Simulate an async operation DispatchQueue.global().async { // Simulate data received let data = "Hello, World!".data(using: .utf8)! // Notify the delegate on the main thread DispatchQueue.main.async { self.delegate?.didReceiveData(data) } } } } // Bridging to AsyncStream struct AsyncDataSource { var dataSource: DataSource func stream() -> AsyncStream { AsyncStream { continuation in dataSource.delegate = DelegateAdapter(continuation: continuation) dataSource.fetchData() } } } final class DelegateAdapter: SomeDelegate { let continuation: AsyncStream.Continuation init(continuation: AsyncStream.Continuation) { self.continuation = continuation } func didReceiveData(_ data: Data) { continuation.yield(data) continuation.finish() // Complete the stream if needed } } // Usage example let dataSource = DataSource() let asyncDataSource = AsyncDataSource(dataSource: dataSource) Task { for await data in asyncDataSource.stream() { if let message = String(data: data, encoding: .utf8) { print(message) // Output: Hello, World! } } }

Swift AsyncStream Delegate Pattern Asynchronous Programming iOS Development