Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/pointfreeco/swift-nonempty

🎁 A compile-time guarantee that a collection contains a value.
https://github.com/pointfreeco/swift-nonempty

collections conditional-conformance swift type-safety

Last synced: 3 months ago
JSON representation

🎁 A compile-time guarantee that a collection contains a value.

Awesome Lists containing this project

README

        

# 🎁 NonEmpty

[![CI](https://github.com/pointfreeco/swift-nonempty/workflows/CI/badge.svg)](https://actions-badge.atrox.dev/pointfreeco/swift-nonempty/goto)
[![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fpointfreeco%2Fswift-nonempty%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/pointfreeco/swift-nonempty)
[![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fpointfreeco%2Fswift-nonempty%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/pointfreeco/swift-nonempty)

A compile-time guarantee that a collection contains a value.

## Motivation

We often work with collections that should _never_ be empty, but the type system makes no such guarantees, so we're forced to handle that empty case, often with `if` and `guard` statements. `NonEmpty` is a lightweight type that can transform _any_ collection type into a non-empty version. Some examples:

```swift
// 1.) A non-empty array of integers
let xs = NonEmpty<[Int]>(1, 2, 3, 4)
xs.first + 1 // `first` is non-optional since it's guaranteed to be present

// 2.) A non-empty set of integers
let ys = NonEmpty>(1, 1, 2, 2, 3, 4)
ys.forEach { print($0) } // => 1, 2, 3, 4

// 3.) A non-empty dictionary of values
let zs = NonEmpty<[Int: String]>((1, "one"), [2: "two", 3: "three"])

// 4.) A non-empty string
let helloWorld = NonEmpty("H", "ello World")
print("\(helloWorld)!") // "Hello World!"
```

## Applications

There are many applications of non-empty collection types but it can be hard to see since the Swift standard library does not give us this type. Here are just a few such applications:

### Strengthen 1st party APIs

Many APIs take and return empty-able arrays when they can in fact guarantee that the arrays are non-empty. Consider a `groupBy` function:

```swift
extension Sequence {
func groupBy(_ f: (Element) -> A) -> [A: [Element]] {
// Unimplemented
}
}

Array(1...10)
.groupBy { $0 % 3 }
// [0: [3, 6, 9], 1: [1, 4, 7, 10], 2: [2, 5, 8]]
```

However, the array `[Element]` inside the return type `[A: [Element]]` can be guaranteed to never be empty, for the only way to produce an `A` is from an `Element`. Therefore the signature of this function could be strengthened to be:

```swift
extension Sequence {
func groupBy
(_ f: (Element) -> A) -> [A: NonEmpty<[Element]>] {
// Unimplemented
}
}
```

### Better interface with 3rd party APIs

Sometimes a 3rd party API we interact with requires non-empty collections of values, and so in our code we should use non-empty types so that we can be sure to never send an empty values to the API. A good example of this is [GraphQL](https://graphql.org/). Here is a very simple query builder and printer:

```swift
enum UserField: String { case id, name, email }

func query(_ fields: Set) -> String {
return (["{"] + fields.map { " \($0.rawValue)" } + ["}"])
.joined()
}

print(query([.name, .email]))
// {
// name
// email
// }

print(query([]))
// {
// }
```

This last query is a programmer error, and will cause the GraphQL server to send back an error because it is not valid to send an empty query. We can prevent this from ever happening by instead forcing our query builder to work with non-empty sets:

```swift
func query(_ fields: NonEmptySet) -> String {
return (["{"] + fields.map { " \($0.rawValue)" } + ["}"])
.joined()
}

print(query(.init(.name, .email)))
// {
// name
// email
// }

print(query(.init()))
// 🛑 Does not compile
```

### More expressive data structures

A popular type in the Swift community (and other languages), is the `Result` type. It allows you to express a value that can be successful or be a failure. There's a related type that is also handy, called the `Validated` type:

```swift
enum Validated {
case valid(Value)
case invalid([Error])
}
```

A value of type `Validated` is either valid, and hence comes with a `Value`, or it is invalid, and comes with an array of errors that describe what all is wrong with the value. For example:

```swift
let validatedPassword: Validated =
.invalid(["Password is too short.", "Password must contain at least one number."])
```

This is useful because it allows you to describe all of the things wrong with a value, not just one thing. However, it doesn't make a lot of sense if we use an empty array of the list of validation errors:

```swift
let validatedPassword: Validated = .invalid([]) // ???
```

Instead, we should strengthen the `Validated` type to use a non-empty array:

```swift
enum Validated {
case valid(Value)
case invalid(NonEmptyArray)
}
```

And now this is a compiler error:

```swift
let validatedPassword: Validated = .invalid(.init([])) // 🛑
```

## Installation

If you want to use NonEmpty in a project that uses [SwiftPM](https://swift.org/package-manager/), it's as simple as adding a dependency to your `Package.swift`:

``` swift
dependencies: [
.package(url: "https://github.com/pointfreeco/swift-nonempty.git", from: "0.3.0")
]
```

## Interested in learning more?

These concepts (and more) are explored thoroughly in [Point-Free](https://www.pointfree.co), a video series exploring functional programming and Swift hosted by [Brandon Williams](https://twitter.com/mbrandonw) and [Stephen Celis](https://twitter.com/stephencelis).

NonEmpty was first explored in [Episode #20](https://www.pointfree.co/episodes/ep20-nonempty):


video poster image

## License

All modules are released under the MIT license. See [LICENSE](LICENSE) for details.