File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed
Sources/AsyncOperations/Optional
Tests/AsyncOperationsTests/Optional Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ extension Optional {
2+ /// An async function of `map`.
3+ /// - Parameter transform: A similar closure with `map`'s one, but it's async.
4+ /// - Returns: A transformed optional.
5+ public func asyncMap< T> ( _ transform: ( Wrapped ) async throws -> T ) async rethrows -> T ? {
6+ guard let value = self else {
7+ return nil
8+ }
9+
10+ return try await transform ( value)
11+ }
12+
13+ /// An async function of `flatMap`.
14+ /// - Parameter transform: A similar closure with `flatMap`'s one, but it's async.
15+ /// - Returns: A transformed optional.
16+ public func asyncFlatMap< T> ( _ transform: ( Wrapped ) async throws -> T ? ) async rethrows -> T ? {
17+ guard let value = self else {
18+ return nil
19+ }
20+
21+ return try await transform ( value)
22+ }
23+ }
Original file line number Diff line number Diff line change 1+ import Testing
2+ import AsyncOperations
3+
4+ struct OptionalAsyncMap {
5+ @Test
6+ func asyncMap( ) async throws {
7+ let nonSendable : NonSendable ? = NonSendable ( )
8+ let result = await nonSendable. asyncMap { $0. number + 1 }
9+ #expect( result == 1 )
10+ }
11+
12+ @Test
13+ func asyncMapForNilCase( ) async throws {
14+ let nonSendable : NonSendable ? = nil
15+ let result = await nonSendable. asyncMap { $0. number + 1 }
16+ #expect( result == nil )
17+ }
18+
19+ @Test
20+ func asyncFlatMap( ) async throws {
21+ let nonSendable : NonSendable ? = NonSendable ( )
22+ let result = await nonSendable. asyncFlatMap { $0. number + 1 }
23+ #expect( result == 1 )
24+ }
25+
26+ @Test
27+ func asyncFlatMapForNilCase( ) async throws {
28+ let nonSendable : NonSendable ? = nil
29+ let result = await nonSendable. asyncFlatMap { $0. number + 1 }
30+ #expect( result == nil )
31+ }
32+
33+ @Test
34+ func asyncFlatMapForNilNilCase( ) async throws {
35+ let nonSendable : NonSendable ? = NonSendable ( )
36+ let result : Int ? = await nonSendable. asyncFlatMap { _ in nil }
37+ #expect( result == nil )
38+ }
39+ }
40+
41+
42+ private class NonSendable {
43+ var number = 0
44+ }
You can’t perform that action at this time.
0 commit comments