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:
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
}
}
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:
extension Sequence {
func groupBy<A>(_ f: (Element) -> A) -> [A: NonEmpty<[Element]>] {
// Unimplemented
}
}
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 (["{"] + 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:
func query(_ fields: NonEmptySet<UserField>) -> String {
return (["{"] + fields.map { " \($0.rawValue)" } + ["}"])
.joined()
}
print(query(.init(.name, .email)))
// {
// name
// email
// }
print(query(.init()))
// 🛑 Does not compile
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 want to use NonEmpty in a project that uses SwiftPM, it's as simple as adding a dependency to your Package.swift
:
dependencies: [
.package(url: "https://github.com/pointfreeco/swift-nonempty.git", from: "0.3.0")
]
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:
All modules are released under the MIT license. See LICENSE for details.