Swift tips #4: Build Arrays Declaratively with ArrayBuilder
Photo by Amza Andrei on Unsplash. I don’t really know what I’m trying to say with this poster
Hey! These are Swift Tips — quick, short, and useful insights about Swift. No fillers, no long reads, no BS. Just useful things you may not know. Today we will talk about arrays and how to build them in Swift.
If you’ve been working with Swift for a while, you know the pain of building arrays in a real-world scenario:
var array = [Int]()
array.append(1)
array.append(2)
if condition {
array.append(3)
}
for i in 4...6 {
array.append(i)
}
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8]
🤮 Looks familiar, right? Every time you want to conditionally add elements, loop over something, or combine arrays, you end up writing imperative hell. It gets messy fast.
But what if I tell you that you actually do this instead:
let numbers: [Int] = buildArray {
1
2
if condition {
3
}
for i in 4...6 {
i
}
[7, 8]
}
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8]
Nice, clean, readable, intuitive — like SwiftUI @ViewBuilder for arrays! Actually it is! But it’s not built-in. There’s been a discussion about whether this magic should be included in Swift’s standard library… https://forums.swift.org/t/add-arraybuilder-to-the-standard-library/83811/23
However, while Swift core team are waiting for the ‘perfect solution’ you can make your code clean right here, right now. No need to wait! :)
Install & Use
1️⃣ Add the package via Swift Package Manager
In your Package.swift:
dependencies: [
.package(url: "https://github.com/kliuchev/ArrayBuilder.git", from: "1.0.0")
]
Then add ArrayBuilder as a dependency of your target:
.target(
name: "MyApp",
dependencies: ["ArrayBuilder"]
)
Or if you use Xcode, just add it as a dependency
2️⃣ Import and start using buildArray
import ArrayBuilder
let numbers: [Int] = buildArray {
1
2
if true {
3
}
}
print(numbers) // [1, 2, 3]
That’s it, now your codebase is 10× more readable, and your job title just leveled up!
👏 Don’t hesitate to give this tip 50 claps
⭐ Give a star on GitHub: https://github.com/kliuchev/ArrayBuilder
Bye!
P.S. For those how want to know how to build your own ArrayBuilder or even YourBestDomainSpecificBuilder
- Here is a source code: https://github.com/kliuchev/ArrayBuilder/blob/main/Sources/ArrayBuilder/ArrayBuilder.swift
- Learn about @resultBuilder here — https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes#resultBuilder