Huffman Coding 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
- ✓Huffman Coding runs in O(n log n) time and O(n) space, in Swift as in every other language.
- ✓There is no heap in the Swift standard library. Apple ships one in swift-collections, whose HeapModule provides Heap, a min-max heap offering popMin and popMax in O(log n); it is a package dependency, not stdlib, and saying otherwise misleads anyone reading your Package.swift.
- ✓The first question in review is what a symbol even is, and Character is the wrong answer. A Swift String iterates grapheme clusters, so one Character can span several scalars and the alphabet has no fixed bound; key the tally on UInt8 or Unicode.Scalar instead.
- ✓The Swift trap: Integer overflow traps here; it does not wrap, and optimisation does not remove the check.
- ✓An indirect enum heap-boxes each recursive case and reference-counts it, so building the tree costs 2n-1 allocations plus retain and release traffic on every copy of a node value, including the copies made by passing it into a recursive function.
What Huffman Coding actually is
Huffman Coding in Swift: what you actually reach for
Swift implementation
// Event-class codes counted off one seismic sensor array.
indirect enum HTree {
case leaf(code: String, w: Int)
case fork(w: Int, lo: HTree, hi: HTree)
// Two patterns, one case: legal only because both bind `w` at the same type.
var weight: Int {
switch self { case .leaf(_, let w), .fork(let w, _, _): return w }
}
}
/// Two-queue construction: after the sort there is no heap at all. Merged weights come
/// out non-decreasing, so `forks` is ordered by construction and the merge is a linear
/// scan of two indices.
func build(_ tally: [(String, Int)]) -> HTree? {
// sorted(by:) has been documented stable since Swift 5, but the explicit tie-break on
// the code keeps the ordering readable and independent of that guarantee.
let leaves = tally.sorted { $0.1 != $1.1 ? $0.1 < $1.1 : $0.0 < $1.0 }
.map { HTree.leaf(code: $0.0, w: $0.1) }
guard leaves.count > 1 else { return leaves.first }
var forks: [HTree] = []
var i = 0, j = 0
func take() -> HTree {
if j == forks.count || (i < leaves.count && leaves[i].weight <= forks[j].weight) {
defer { i += 1 }; return leaves[i]
}
defer { j += 1 }; return forks[j]
}
while (leaves.count - i) + (forks.count - j) > 1 {
let a = take(), b = take()
// Int + Int traps on overflow in release builds too; &+ would wrap instead.
forks.append(.fork(w: a.weight + b.weight, lo: a, hi: b))
}
return forks.last
}
func depths(_ t: HTree, _ d: Int, into out: inout [String: Int]) {
switch t {
case .leaf(let code, _): out[code] = max(d, 1) // max covers a one-symbol alphabet
case .fork(_, let lo, let hi):
depths(lo, d + 1, into: &out); depths(hi, d + 1, into: &out)
}
}
var lengths: [String: Int] = [:]
if let root = build([("ML", 4310), ("LP", 902), ("VT", 431), ("EQ", 88), ("EX", 12)]) {
depths(root, 0, into: &lengths)
}
print(lengths.sorted { $0.value != $1.value ? $0.value < $1.value : $0.key < $1.key })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 log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Huffman Coding?
There is no heap in the Swift standard library. Apple ships one in swift-collections, whose HeapModule provides Heap, a min-max heap offering popMin and popMax in O(log n); it is a package dependency, not stdlib, and saying otherwise misleads anyone reading your Package.swift. Without it the available pieces are Dictionary for the tally, sorted(by:) for the initial order, and Array for both queues. An indirect enum states the tree directly: the compiler boxes the recursive payload and checks the switch for exhaustiveness.
What is the most common Swift mistake when implementing Huffman Coding?
Integer overflow traps here; it does not wrap, and optimisation does not remove the check. The root's weight is the sum of every count in the alphabet, so with counts held in a narrow type the failure lands on the final merge, after every earlier merge succeeded and every small-input unit test passed: the process dies with a Swift runtime failure and SIGTRAP rather than returning a nonsense number. Building with -O changes nothing, since only &+ wraps and only -Ounchecked drops the check. Widening the accumulator is the real fix, because the running total needs more range than any individual count does.
How does Huffman Coding actually perform in Swift?
An indirect enum heap-boxes each recursive case and reference-counts it, so building the tree costs 2n-1 allocations plus retain and release traffic on every copy of a node value, including the copies made by passing it into a recursive function. The two-queue construction sidesteps a priority queue completely: sorted(by:) is O(n log n), and the merge phase after it is one linear pass over two arrays with no comparator closure, no sift, and no allocation beyond the fork nodes themselves. Time complexity is O(n log 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 trialBefore paying for Devin, check its student and free-tier options 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.