Created
December 24, 2023 21:11
-
-
Save simonbromberg/13bcc9ab6f41a12eeeb37dd170dfe91c to your computer and use it in GitHub Desktop.
AsyncMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Optional { | |
func asyncMap<T>( | |
transform: (Wrapped) async throws -> T | |
) async rethrows -> T? { | |
guard case let .some(value) = self else { | |
return nil | |
} | |
return try await transform(value) | |
} | |
} | |
// https://www.swiftbysundell.com/articles/async-and-concurrent-forEach-and-map/ | |
public extension Sequence { | |
func asyncMap<T>( | |
_ transform: (Element) async throws -> T | |
) async rethrows -> [T] { | |
var values = [T]() | |
for element in self { | |
try await values.append(transform(element)) | |
} | |
return values | |
} | |
func asyncForEach( | |
_ operation: (Element) async throws -> Void | |
) async rethrows { | |
for element in self { | |
try await operation(element) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment