From 35024e983a7397e2548739c9cfdd3f91cfd0e932 Mon Sep 17 00:00:00 2001 From: Red Davis Date: Fri, 15 Jul 2022 06:01:01 +0100 Subject: [PATCH] feat: add last() to async sequence (#36) --- .../Extensions/AsyncSequence+Extension.swift | 10 ++++++++++ .../Tests/Extensions/AsyncSequenceTests.swift | 11 +++++++++-- README.md | 16 ++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Asynchrone/Source/Extensions/AsyncSequence+Extension.swift b/Asynchrone/Source/Extensions/AsyncSequence+Extension.swift index 0d40e57..ede5558 100644 --- a/Asynchrone/Source/Extensions/AsyncSequence+Extension.swift +++ b/Asynchrone/Source/Extensions/AsyncSequence+Extension.swift @@ -50,6 +50,16 @@ extension AsyncSequence { } } + /// The last element of the sequence, if there is one. + public func last() async rethrows -> Element? { + var latestElement: Element? + for try await element in self { + latestElement = element + } + + return latestElement + } + /// Collect elements from a sequence. /// /// ```swift diff --git a/AsynchroneTests/Tests/Extensions/AsyncSequenceTests.swift b/AsynchroneTests/Tests/Extensions/AsyncSequenceTests.swift index 4e9e261..6e09a8e 100644 --- a/AsynchroneTests/Tests/Extensions/AsyncSequenceTests.swift +++ b/AsynchroneTests/Tests/Extensions/AsyncSequenceTests.swift @@ -28,8 +28,15 @@ final class AsyncSequenceTests: XCTestCase { // MARK: First func testFirst() async { - let firstValue = await self.sequence.first() - XCTAssertEqual(firstValue, 1) + let element = await self.sequence.first() + XCTAssertEqual(element, 1) + } + + // MARK: Last + + func testLast() async { + let element = await self.sequence.last() + XCTAssertEqual(element, 3) } // MARK: Collect diff --git a/README.md b/README.md index 8d7ca14..8523e9d 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,22 @@ print(await sequence.first()) // 1 ``` +#### Last + +```swift +let sequence = AsyncStream { continuation in + continuation.yield(1) + continuation.yield(2) + continuation.yield(3) + continuation.finish() +} + +print(await sequence.last()) + +// Prints: +// 3 +``` + #### Collect ```swift