Skip to content

Instantly share code, notes, and snippets.

@tkersey
Last active March 14, 2024 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkersey/52ecd34ace5b7226ddd6adf03cfbefa2 to your computer and use it in GitHub Desktop.
Save tkersey/52ecd34ace5b7226ddd6adf03cfbefa2 to your computer and use it in GitHub Desktop.
Missing async functions
extension Optional {
func map<T>(
transform: (Wrapped) async throws -> T
) async rethrows -> T? {
guard case let .some(value) = self else { return nil }
return try await transform(value)
}
}
extension Sequence {
func map<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 compactMap<T>(
_ transform: (Element) async throws -> T?
) async rethrows -> [T] {
var values = [T]()
for element in self {
if let newElement = try await transform(element) {
values.append(newElement)
}
}
return values
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment