Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Sources/AsyncOperations/Optional/Optional+asyncMap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
extension Optional {
/// An async function of `map`.
/// - Parameter transform: A similar closure with `map`'s one, but it's async.
/// - Returns: A transformed optional.
public func asyncMap<T>(_ transform: (Wrapped) async throws -> T) async rethrows -> T? {
guard let value = self else {
return nil
}

return try await transform(value)
}

/// An async function of `flatMap`.
/// - Parameter transform: A similar closure with `flatMap`'s one, but it's async.
/// - Returns: A transformed optional.
public func asyncFlatMap<T>(_ transform: (Wrapped) async throws -> T?) async rethrows -> T? {
guard let value = self else {
return nil
}

return try await transform(value)
}
}
44 changes: 44 additions & 0 deletions Tests/AsyncOperationsTests/Optional/OptionalAsyncMap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Testing
import AsyncOperations

struct OptionalAsyncMap {
@Test
func asyncMap() async throws {
let nonSendable: NonSendable? = NonSendable()
let result = await nonSendable.asyncMap { $0.number + 1 }
#expect(result == 1)
}

@Test
func asyncMapForNilCase() async throws {
let nonSendable: NonSendable? = nil
let result = await nonSendable.asyncMap { $0.number + 1 }
#expect(result == nil)
}

@Test
func asyncFlatMap() async throws {
let nonSendable: NonSendable? = NonSendable()
let result = await nonSendable.asyncFlatMap { $0.number + 1 }
#expect(result == 1)
}

@Test
func asyncFlatMapForNilCase() async throws {
let nonSendable: NonSendable? = nil
let result = await nonSendable.asyncFlatMap { $0.number + 1 }
#expect(result == nil)
}

@Test
func asyncFlatMapForNilNilCase() async throws {
let nonSendable: NonSendable? = NonSendable()
let result: Int? = await nonSendable.asyncFlatMap { _ in nil }
#expect(result == nil)
}
}


private class NonSendable {
var number = 0
}