Skip to content
🎁 A compile-time guarantee that a collection contains a value.
Swift Ruby Makefile
Branch: master
Clone or download
jandamm and stephencelis Add generic-backend compatible Coding (#14)
* Add Decodable with check for empty head

* Add tests for new codable

* Fix identation

* Change NonEmptyCodable implementation

* Refactor NonEmptyCodable to not shadow stdlib

The previous implementation added a requirement for append to decodable
types. While this made adoption easier for types which come with append
it may add some confusion for types where append isn't implemented
already and would only be introduced for Coding.

Co-authored-by: Stephen Celis <>
Latest commit 9ef8c4a Feb 21, 2020


Type Name Latest commit message Commit time
Failed to load latest commit information.
.github/workflows Use GitHub Actions (#25) Jan 30, 2020
.swiftpm/xcode/package.xcworkspace Use GitHub Actions (#25) Jan 30, 2020
NonEmpty.xcodeproj Add generic-backend compatible Coding (#14) Feb 21, 2020
NonEmpty.xcworkspace 🎁 NonEmpty Jun 25, 2018
Sources/NonEmpty Add generic-backend compatible Coding (#14) Feb 21, 2020
Tests/NonEmptyTests Add generic-backend compatible Coding (#14) Feb 21, 2020
.gitignore 🎁 NonEmpty Jun 25, 2018
Info.plist Add Info.plist (#11) Jan 8, 2019
Makefile Use GitHub Actions (#25) Jan 30, 2020
Package.swift Use GitHub Actions (#25) Jan 30, 2020 Use GitHub Actions (#25) Jan 30, 2020
project.yml Safe on application extensions fix (#18) Sep 18, 2019

🎁 NonEmpty

Swift 5 Build Status @pointfreeco

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


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:

// 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<Set<Int>>(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<String>("H", "ello World")
print("\(helloWorld)!") // "Hello World!"


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:

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

  .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:

extension Sequence {
  func groupBy<A>(_ 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. Here is a very simple query builder and printer:

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

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

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

// {
// }

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:

func query(_ fields: NonEmptySet<UserField>) -> String {
  return (["{"] + { "  \($0.rawValue)" } + ["}"])

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

// πŸ›‘ 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:

enum Validated<Value, Error> {
  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:

let validatedPassword: Validated<String, String> =
  .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:

let validatedPassword: Validated<String, String> = .invalid([]) // ???

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

enum Validated<Value, Error> {
  case valid(Value)
  case invalid(NonEmptyArray<Error>)

And now this is a compiler error:

let validatedPassword: Validated<String, String> = .invalid(.init([])) // πŸ›‘



If you use Carthage, you can add the following dependency to your Cartfile:

github "pointfreeco/swift-nonempty" ~> 0.2


If your project uses CocoaPods, just add the following to your Podfile:

pod 'NonEmpty', '~> 0.2'


If you want to use NonEmpty in a project that uses SwiftPM, it's as simple as adding a dependencies clause to your Package.swift:

dependencies: [
  .package(url: "", from: "0.2.0")

Xcode Sub-project

Submodule, clone, or download NonEmpty, and drag NonEmpty.xcodeproj into your project.

Interested in learning more?

These concepts (and more) are explored thoroughly in Point-Free, a video series exploring functional programming and Swift hosted by Brandon Williams and Stephen Celis.

NonEmpty was first explored in Episode #20:

video poster image


All modules are released under the MIT license. See LICENSE for details.

You can’t perform that action at this time.