Add async Collection extensions

This commit is contained in:
Daniel Saidi 2021-11-10 23:41:28 +01:00
parent 9505a4ff73
commit a2bd714cbb
2 changed files with 54 additions and 0 deletions

View File

@ -12,6 +12,7 @@ This version also introduces a new `StoreKit` namespace with handy utils for man
### ✨ New features ### ✨ New features
* `Bundle` has a new `displayName` extension. * `Bundle` has a new `displayName` extension.
* `Collection` has new `asyncCompactMap` and `asyncMap` extensions.
* `Date` has a new `components` extension for retrieving year, month, hour etc. * `Date` has a new `components` extension for retrieving year, month, hour etc.
* `String` has new `boolValue` extension. * `String` has new `boolValue` extension.

View File

@ -0,0 +1,53 @@
//
// Collection+Async.swift
// SwiftKit
//
// Created by Daniel Saidi on 2021-11-10.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
@available(iOS 15.0, macOS 12.0, watchOS 8.0, tvOS 15.0, *)
public extension Collection {
/**
Compact map a collection using an async transform.
*/
func asyncCompactMap<ResultType>(_ transform: (Element) async -> ResultType?) async -> [ResultType] {
await self
.asyncMap(transform)
.compactMap { $0 }
}
/**
Compact map a collection using an async transform.
*/
func asyncCompactMap<ResultType>(_ transform: (Element) async throws -> ResultType?) async throws -> [ResultType] {
try await self
.asyncMap(transform)
.compactMap { $0 }
}
/**
Map a collection using an async transform.
*/
func asyncMap<ResultType>(_ transform: (Element) async -> ResultType) async -> [ResultType] {
var result = [ResultType]()
for item in self {
await result.append(transform(item))
}
return result
}
/**
Map a collection using an async transform.
*/
func asyncMap<ResultType>(_ transform: (Element) async throws -> ResultType) async throws -> [ResultType] {
var result = [ResultType]()
for item in self {
try await result.append(transform(item))
}
return result
}
}