A collection of useful result builders for Swift and Foundation value types.
Motivation
Arrays, dictionaries, and other collection-based types in Swift are relatively simple to construct and mutate.
However, things get tricky when the contained elements depend on certain conditions or awkward logic. A prime example of this is constructing a payload to send to an analytics service. The resulting code might look like this:
It’s not bad, but it’s definitely not as Swifty as one would expect.
We’re sprinkling imperative code on what should just be a description of our payload. Not only does this make it harder to reason about the code at a glance, but it also leaves too much leeway for unintended mutations.
Thankfully, there’s a better way…
Getting started
Swift Builders enables result builder syntax for most Collection types in Swift and Foundation.
For example, by leveraging Dictionary.build, our use case above becomes:
We can even annotate our function with the @DictionaryBuilder attribute to make the function body behave like the builder body itself (think @ViewBuilder):
Swift Builders
A collection of useful result builders for Swift and Foundation value types.
Motivation
Arrays, dictionaries, and other collection-based types in Swift are relatively simple to construct and mutate.
However, things get tricky when the contained elements depend on certain conditions or awkward logic. A prime example of this is constructing a payload to send to an analytics service. The resulting code might look like this:
It’s not bad, but it’s definitely not as Swifty as one would expect.
We’re sprinkling imperative code on what should just be a description of our payload. Not only does this make it harder to reason about the code at a glance, but it also leaves too much leeway for unintended mutations.
Thankfully, there’s a better way…
Getting started
Swift Builders enables result builder syntax for most
Collection
types in Swift and Foundation.For example, by leveraging
Dictionary.build
, our use case above becomes:We can even annotate our function with the
@DictionaryBuilder
attribute to make the function body behave like the builder body itself (think@ViewBuilder
):This is only a small demonstration of the power of result builders applied to Swift’s native types.
The library offers a variety of builders out of the box:
ArrayBuilder
ArraySliceBuilder
ContiguousArrayBuilder
DataBuilder
DictionaryBuilder
SetBuilder
SliceBuilder
StringBuilder
StringUTF8ViewBuilder
StringUnicodeScalarViewBuilder
SubstringBuilder
SubstringUTF8ViewBuilder
SubstringUnicodeScalarViewBuilder
Benchmarks