• Stars
    star
    730
  • Rank 59,832 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 2 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.

CollectionConcurrencyKit

Welcome to CollectionConcurrencyKit, a lightweight Swift package that adds asynchronous and concurrent versions of the standard map, flatMap, compactMap, and forEach APIs to all Swift collections that conform to the Sequence protocol. That includes built-in types, like Array, Set and, Dictionary, as well as any custom collections that conform to that protocol.

CollectionConcurrencyKit can be used to implement high-performance data processing and algorithms in a way that fully utilizes Swift’s built-in concurrency system. It’s heavily unit tested, fully documented, and used in production to generate swiftbysundell.com.

Asynchronous iterations

The async variants of CollectionConcurrencyKit’s APIs enable you to call async-marked functions within your various mapping and forEach iterations, while still maintaining a completely predictable, sequential execution order.

For example, here’s how we could use asyncMap to download a series of HTML strings from a collection of URLs:

let urls = [
    URL(string: "https://apple.com")!,
    URL(string: "https://swift.org")!,
    URL(string: "https://swiftbysundell.com")!
]

let htmlStrings = try await urls.asyncMap { url -> String in
    let (data, _) = try await URLSession.shared.data(from: url)
    return String(decoding: data, as: UTF8.self)
}

And here’s how we could use asyncCompactMap to ignore any download that failed, by returning an optional value, rather than throwing an error:

let htmlStrings = await urls.asyncCompactMap { url -> String? in
    do {
        let (data, _) = try await URLSession.shared.data(from: url)
        return String(decoding: data, as: UTF8.self)
    } catch {
        return nil
    }
}

Each of CollectionConcurrencyKit’s APIs come in both throwing and non-throwing variants, so since the above call to asyncCompactMap doesn’t throw, we don’t need to use try when calling it.

Concurrency

CollectionConcurrencyKit also includes concurrent variants of forEach, map, flatMap, and compactMap, which perform their iterations in parallel, while still maintaining a predictable order when producing their results.

For example, since our above HTML downloading code consists of completely separate operations, we could instead use concurrentMap to perform each of those operations in parallel for a significant speed boost:

let htmlStrings = try await urls.concurrentMap { url -> String in
    let (data, _) = try await URLSession.shared.data(from: url)
    return String(decoding: data, as: UTF8.self)
}

And if we instead wanted to parallelize our asyncCompactMap-based variant of the above code, then we could do so by using concurrentCompactMap:

let htmlStrings = await urls.concurrentCompactMap { url -> String? in
    do {
        let (data, _) = try await URLSession.shared.data(from: url)
        return String(decoding: data, as: UTF8.self)
    } catch {
        return nil
    }
}

Regardless of whether we choose the async or concurrent versions of CollectionConcurrencyKit’s APIs, the order of the returned results is always guaranteed to be the exact same as when calling the standard library’s non-async versions of those APIs. So, the order of the htmlStrings array will be identical across all of the above four code samples (ignoring any nil values produced by the compactMap-variants).

What APIs are included?

CollectionConcurrencyKit adds the following APIs to all Sequence-conforming Swift collections:

  • Async variants that perform each of their operations in sequence, one after the other:
    • asyncForEach
    • asyncMap
    • asyncCompactMap
    • asyncFlatMap
  • Concurrent variants that perform each of their operations in parallel (while still maintaining a predictable output order):
    • concurrentForEach
    • concurrentMap
    • concurrentCompactMap
    • concurrentFlatMap

Both throwing and non-throwing versions of all of the above APIs are included. To learn more about map, flatMap, and compactMap in general, check out this article.

System requirements

CollectionConcurrencyKit works on all operating system versions that support Swift’s concurrency system, which includes iOS 13+, macOS 10.15+, watchOS 6+, and tvOS 13+, as well as Linux (when using a Swift toolchain of version 5.5 or higher). Note that you need to use Xcode 13.2 or later when using CollectionConcurrencyKit on Apple’s platforms.

Installation

CollectionConcurrencyKit is distributed using the Swift Package Manager. To install it within another Swift package, add it as a dependency within your Package.swift manifest:

let package = Package(
    ...
    dependencies: [
        .package(url: "https://github.com/JohnSundell/CollectionConcurrencyKit.git", from: "0.1.0")
    ],
    ...
)

If you’d like to use CollectionConcurrencyKit within an iOS, macOS, watchOS or tvOS app, then use Xcode’s File > Add Packages... menu command to add it to your project.

Then import CollectionConcurrencyKit wherever you’d like to use it:

import CollectionConcurrencyKit

For more information on how to use the Swift Package Manager, check out this article, or its official documentation.

Support and contributions

CollectionConcurrencyKit has been made freely available to the entire Swift community under the very permissive MIT license, but please note that it doesn’t come with any official support channels, such as GitHub issues, or Twitter/email-based support. So, before you start using CollectionConcurrencyKit within one of your projects, it’s highly recommended that you spend some time familiarizing yourself with its implementation, in case you’ll run into any issues that you’ll need to debug.

If you’ve found a bug, documentation typo, or if you want to propose a performance improvement, then feel free to open a Pull Request (even if it just contains a unit test that reproduces a given issue). While all sorts of fixes and tweaks are more than welcome, CollectionConcurrencyKit is meant to be a very small, focused library, so it’s considered more or less feature-complete. So, if you’d like to add any significant new features to the library, then it’s recommended that you fork it, which will let you extend and customize it to fit your needs.

Hope you’ll enjoy using CollectionConcurrencyKit!

More Repositories

1

Publish

A static site generator for Swift developers
Swift
4,763
star
2

SwiftTips

A collection of Swift tips & tricks that I've shared on Twitter
3,971
star
3

Files

A nicer way to handle files & folders in Swift
Swift
2,456
star
4

Ink

A fast and flexible Markdown parser written in Swift.
Swift
2,336
star
5

Unbox

[Deprecated] The easy to use Swift JSON decoder
Swift
1,956
star
6

Plot

A DSL for writing type-safe HTML, XML and RSS in Swift.
Swift
1,946
star
7

Marathon

[DEPRECATED] Marathon makes it easy to write, run and manage your Swift scripts 🏃
Swift
1,869
star
8

ImagineEngine

A project to create a blazingly fast Swift game engine that is a joy to use 🚀
Swift
1,818
star
9

SwiftPlate

Easily generate cross platform Swift framework projects from the command line
Swift
1,766
star
10

Splash

A fast, lightweight and flexible Swift syntax highlighter for blogs, tools and fun!
Swift
1,735
star
11

TestDrive

Quickly try out any Swift pod or framework in a playground
Swift
1,597
star
12

Codextended

Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️
Swift
1,488
star
13

ShellOut

Easily run shell commands from a Swift script or command line tool
Swift
836
star
14

Wrap

[DEPRECATED] The easy to use Swift JSON encoder
Swift
732
star
15

Sweep

Fast and powerful Swift string scanning made simple
Swift
531
star
16

Playground

Instantly create Swift playgrounds from the command line
Swift
439
star
17

Require

Require optional values to be non-nil, or crash gracefully
Swift
414
star
18

XcodeTheme

My Xcode theme - Sundell's Colors
Swift
408
star
19

AsyncCompatibilityKit

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.
Swift
377
star
20

Shapeshift

Quickly convert a folder containing Swift files into an iPad-compatible Playground
Swift
339
star
21

Identity

🆔 Type-safe identifiers in Swift
Swift
298
star
22

SwiftBySundell

Code samples from the Swift by Sundell website & podcast
Swift
289
star
23

SwiftScripting

A list of Swift scripting tools, frameworks & examples
235
star
24

SuperSpriteKit

Extensions to Apple's SpriteKit game engine
Objective-C
224
star
25

Flow

Operation Oriented Programming in Swift
Swift
217
star
26

Xgen

A Swift package for generating Xcode workspaces & playgrounds
Swift
189
star
27

IndieSupportWeeks

A two-week effort to help support indie developers shipping apps on Apple's platforms who have been financially impacted by the COVID-19 pandemic.
183
star
28

CGOperators

Easily manipulate CGPoints, CGSizes and CGVectors using math operators
Swift
148
star
29

Animate

Declarative UIView animations without nested closures
Swift
129
star
30

SplashPublishPlugin

A Splash plugin for the Publish static site generator
Swift
92
star
31

Assert

A collection of convenient assertions for Swift testing
Swift
69
star
32

UITestingExample

Example code from my blog post about UI testing
Swift
67
star
33

Marathon-Examples

A collection of example Swift scripts that can easily be run using Marathon
Swift
55
star
34

Releases

A Swift package for resolving released versions from a Git repository
Swift
51
star
35

BlockSnippets

Xcode snippets that are very handy when working with blocks in various contexts
51
star
36

PlotPlayground

A Swift playground that comes pre-loaded with Plot, that can be used to explore the new component API.
Swift
49
star
37

SwiftKit

A collection of Swift utilities that I share across my Swift-based projects
Swift
38
star
38

UnitTestingWorkshop

Project used during my workshop "Getting started with unit testing in Swift"
Swift
36
star
39

JSUpdateLookup

A lightweight, easy to use Objective-C class to check if your iOS app has an update available
Objective-C
28
star
40

SwiftAveiro

Skeleton project for my Swift Aveiro workshop "Everyone is an API designer"
Swift
15
star
41

CloudKitChat

A demo chat application powered by CloudKit
Objective-C
14
star
42

swiftbysundell-beta-feedback

Submit your feedback on the Swift by Sundell 2.0 beta
9
star
43

JSGeometry

A set of utility functions that enables easy one-line manipulation of CoreGraphics geometry structs like CGPoint, CGSize & CGRect.
Objective-C
6
star
44

JSAutoCopy

An Objective-C category that enables automatic copying of any object
Objective-C
4
star
45

UnboxDemoPlayground

A Swift Playground that comes setup with Unbox & Wrap, used in my CocoaHeads Stockholm presentation
Swift
3
star
46

JSAutoEncodedObject

Automatically encode or decode any Objective-C object
Objective-C
3
star
47

JSLocalization

An Objective-C class that enables dynamic localization of an iOS app.
Objective-C
3
star
48

MarathonTestScriptWithDependencies

A test script with dependencies - used for Marathon's tests
Swift
2
star
49

JSObservableObject

Easily add protocol-based observation to any Objective-C class
Objective-C
2
star
50

swift-source-compat-suite

The infrastructure and project index comprising the Swift source compatibility suite.
Python
2
star
51

MarathonTestPackage

A Swift package that's used in Marathon's tests
Swift
1
star
52

MarathonTestScript

A Swift script that's used in Marathon's tests
Swift
1
star