Red-Black Tree 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
- ✓Red-Black Tree runs in O(log n) time and O(n) space, in Swift as in every other language.
- ✓Nothing. Dictionary and Set are hash tables whose iteration order is randomised per process, and the standard library ships no tree and no ordered collection of any kind.
- ✓Use a sorted Array with a binary-search helper, since that is what the language actually gives you, and reach for Apple swift-collections only after checking what the type you want really is.
- ✓The Swift trap: The name to be careful with is TreeDictionary in swift-collections. Despite the word tree, it is not an ordered structure: it is a persistent hash-array-mapped trie, a design chosen for cheap structural sharing between versions rather than for ordering, and its iteration order is not key order.
- ✓Array is contiguous with copy-on-write, so a sorted array binary-searches entirely in cache and beats any node tree well past ten thousand elements.
What Red-Black Tree actually is
Red-Black Tree in Swift: what you actually reach for
Swift implementation
// Swift ships NO tree and NO ordered collection. This is the honest answer.
struct SortedMap<Key: Comparable, Value> {
private var keys: [Key] = []
private var values: [Value] = []
/// The standard library has no binary search either, so this is step one.
private func lowerBound(_ key: Key) -> Int {
var lo = 0, hi = keys.count
while lo < hi {
let mid = lo + (hi - lo) / 2
if keys[mid] < key { lo = mid + 1 } else { hi = mid }
}
return lo
}
subscript(key: Key) -> Value? {
get {
let i = lowerBound(key)
return i < keys.count && keys[i] == key ? values[i] : nil
}
set {
let i = lowerBound(key)
if i < keys.count && keys[i] == key {
if let newValue { values[i] = newValue }
else { keys.remove(at: i); values.remove(at: i) }
} else if let newValue {
keys.insert(key, at: i)
values.insert(newValue, at: i)
}
}
}
/// Ordered range scan, what a Dictionary cannot do at all.
func range(_ lo: Key, _ hi: Key) -> [(Key, Value)] {
let start = lowerBound(lo)
var end = lowerBound(hi)
while end < keys.count && keys[end] == hi { end += 1 }
return (start..<end).map { (keys[$0], values[$0]) }
}
}
// NAMING TRAP: swift-collections' TreeDictionary is NOT an ordered tree.
// It is a persistent hash-array-mapped trie, built for cheap structural
// sharing between versions, and its iteration order is NOT key order.
// It compiles, it runs, every lookup is correct, and the ordering you
// reached for is simply absent.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(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Red-Black Tree?
Nothing. Dictionary and Set are hash tables whose iteration order is randomised per process, and the standard library ships no tree and no ordered collection of any kind.
What is the most common Swift mistake when implementing Red-Black Tree?
The name to be careful with is TreeDictionary in swift-collections. Despite the word tree, it is not an ordered structure: it is a persistent hash-array-mapped trie, a design chosen for cheap structural sharing between versions rather than for ordering, and its iteration order is not key order. Reaching for it because you wanted sorted iteration gives you a collection that compiles, runs, returns correct lookups and iterates in an order that has nothing to do with your keys, which is exactly the kind of wrong that survives code review. If you want ordering in this ecosystem, sort an array or bring your own tree.
How does Red-Black Tree actually perform in Swift?
Array is contiguous with copy-on-write, so a sorted array binary-searches entirely in cache and beats any node tree well past ten thousand elements. A class-based tree additionally pays automatic reference counting traffic on every link assignment, which on a rotation-heavy write path is a real cost that has no analogue in the garbage-collected languages here. Time complexity is O(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 trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
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.