vsanthanam/arraybuilder
A declarative library for composing arrays in Swift
Overview
ArrayBuilder is SwiftUI for arrays. It provides a generic result builder, ArrayBuilder<T>, that lets you build an array the way you build a view hierarchy with @ViewBuilder — one element per line, with if, else, switch, and for statements mixed right in.
Build an array with the included Array initializer:
let numbers = Array {
if includeZero {
0
}
1
[2, 3]
for value in 4 ... 6 {
value
}
}
// [0, 1, 2, 3, 4, 5, 6] if includeZero is trueOr apply the builder to a function, a computed property, or a closure parameter in your own API:
@ArrayBuilder<String>
var groceries: [String] {
"Milk"
"Eggs"
"Bread"
}ArrayBuilder's declarative approach offers significant advantages over traditional imperative array construction.
Building command line arguments, without ArrayBuilder:
func arguments(verbose: Bool, files: [String]) -> [String] {
var arguments = ["build"]
if verbose {
arguments.append("--verbose")
}
for file in files {
arguments.append("--file")
arguments.append(file)
}
return arguments
}With ArrayBuilder:
@ArrayBuilder<String>
func arguments(verbose: Bool, files: [String]) -> [String] {
"build"
if verbose {
"--verbose"
}
for file in files {
"--file"
file
}
}The declarative approach more closely resembles the final shape of the array, making it easier to read, maintain, and modify. It eliminates the mutable state, append(_:) calls, and explicit return that imperative construction requires, especially when the array depends on conditions, loops, or a mix of single values and other collections.
Installation
ArrayBuilder is currently distributed exclusively through the Swift Package Manager.
To add ArrayBuilder as a dependency to an existing Swift package, add the following line of code to the dependencies parameter of your Package.swift file:
dependencies: [
.package(
url: "https://github.com/vsanthanam/ArrayBuilder.git",
from: "1.0.0"
)
]To add ArrayBuilder as a dependency to an Xcode Project:
- Choose
File→Add Packages... - Enter package URL
https://github.com/vsanthanam/ArrayBuilder.gitand select your release of choice.
Other distribution mechanisms like CocoaPods or Carthage may be added in the future.
Usage & Documentation
ArrayBuilder's documentation is built with DocC and included in the repository.
Additional installation instructions are available on the Swift Package Index
Explore the documentation for more details.
License
ArrayBuilder is available under the MIT license. See the LICENSE file for more information.
Package Metadata
Repository: vsanthanam/arraybuilder
Default branch: main
README: README.md