Custom result builder declaration in Swift - Time & Space Complexity
When we create a custom result builder in Swift, it helps us combine multiple pieces of code into one result.
We want to understand how the time it takes to build the result changes as we add more pieces.
Analyze the time complexity of the following code snippet.
@resultBuilder
struct MyBuilder {
static func buildBlock(_ components: String...) -> String {
components.joined(separator: ", ")
}
}
func makeSentence(@MyBuilder content: () -> String) -> String {
content()
}
let sentence = makeSentence {
"Hello"
"world"
"from"
"Swift"
}
print(sentence)
This code defines a simple custom result builder that joins strings together, then uses it to build a sentence.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Joining an array of strings using
joined(separator:). - How many times: The join operation processes each string once, so it runs once over all input strings.
As we add more strings to the builder, the join operation must combine all of them into one string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Processes 10 strings once |
| 100 | Processes 100 strings once |
| 1000 | Processes 1000 strings once |
Pattern observation: The work grows directly with the number of strings added.
Time Complexity: O(n)
This means the time to build the result grows linearly with the number of components.
[X] Wrong: "The builder runs once per string, so time grows faster than linearly."
[OK] Correct: The builder collects all strings first, then joins them in one step, so it only processes the list once.
Understanding how custom builders combine multiple inputs helps you reason about code efficiency and scalability in real projects.
"What if the builder combined nested arrays of strings instead of a flat list? How would the time complexity change?"