Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Created December 24, 2023 21:11
Show Gist options
  • Save simonbromberg/13bcc9ab6f41a12eeeb37dd170dfe91c to your computer and use it in GitHub Desktop.
Save simonbromberg/13bcc9ab6f41a12eeeb37dd170dfe91c to your computer and use it in GitHub Desktop.
AsyncMap
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