Composite Pattern Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Composite Pattern runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓A protocol with the composite operation, adopted by a leaf struct and a branch struct holding an array of the existential.
- ✓Model the tree as an indirect enum when nodes are pure data, because you get value semantics, exhaustive switching and no reference counting at all; use classes only when nodes have identity or need parent links.
- ✓The Swift trap: A parent pointer declared as a strong reference creates an ARC cycle: the parent holds the child in its array and the child holds the parent back, so neither refcount ever reaches zero and the whole tree leaks silently, with no crash and nothing in the console.
- ✓An indirect enum allocates one box per recursive payload, so a tree of them costs an allocation per branch, similar to Box in Rust; a struct holding an Array of children has one allocation per array instead.
What Composite Pattern actually is
Composite Pattern in Swift: what you actually reach for
Swift implementation
// Value-type tree: indirect boxes the recursive payload so the enum has a finite size.
indirect enum Node {
case leaf(Int)
case branch([Node])
var total: Int {
switch self {
case .leaf(let n): return n
case .branch(let kids): return kids.reduce(0) { $0 + $1.total }
}
}
}
// Reference-type tree: the back link MUST be weak or the tree leaks.
final class TreeNode {
var size: Int
private(set) var children: [TreeNode] = []
weak var parent: TreeNode? // strong here = ARC cycle, silent leak
init(size: Int) { self.size = size }
func add(_ child: TreeNode) {
child.parent = self
children.append(child)
}
}
extension TreeNode: Sequence {
func makeIterator() -> AnyIterator<TreeNode> {
var stack = [self] // explicit stack, no recursive boxing
return AnyIterator {
guard let n = stack.popLast() else { return nil }
stack.append(contentsOf: n.children)
return n
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Composite Pattern?
A protocol with the composite operation, adopted by a leaf struct and a branch struct holding an array of the existential. For a value-type tree, an enum needs the indirect keyword so the compiler boxes the recursive payload and the type gets a finite size. Sequence and IteratorProtocol conformance gives for-in and the whole standard-library algorithm surface, and FileManager.enumerator is the platform composite walker.
What is the most common Swift mistake when implementing Composite Pattern?
A parent pointer declared as a strong reference creates an ARC cycle: the parent holds the child in its array and the child holds the parent back, so neither refcount ever reaches zero and the whole tree leaks silently, with no crash and nothing in the console. weak var parent is the fix, and unowned is the wrong choice here because a child can genuinely outlive a detached parent and unowned turns that into a crash. The related trap is that deinit on a deeply nested class tree recurses, so releasing a very deep tree can overflow the stack inside ARC teardown.
How does Composite Pattern actually perform in Swift?
An indirect enum allocates one box per recursive payload, so a tree of them costs an allocation per branch, similar to Box in Rust; a struct holding an Array of children has one allocation per array instead. Calls through any Node use a protocol witness table and cannot inline, whereas a generic function constrained to the protocol specialises under whole-module optimisation. Marking node classes final removes dynamic dispatch on their methods and is one of the highest-yield single-word changes in a Swift tree implementation. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.