Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Autocomplete Implementation in Swift

14 min readintermediate
Website QA and SEO audits

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

  • ✓Trie Autocomplete runs in O(m) time and O(n*m) space, in Swift as in every other language.
  • ✓The Swift standard library has no trie. The node is a final class holding var children: [Character: TrieNode].
  • ✓The node is declared final class, never struct, and final is not optional style: it lets the optimizer devirtualize property access.
  • ✓The Swift trap: Declare the node as a struct and the algorithm quietly stops working, but not for the reason people first guess.
  • ✓Every node = next in the descent is a retain/release pair unless the optimizer proves the lifetime, so ARC traffic, not hashing, is usually the top of the profile in a whole-module-optimisation build; marking the class final and the properties non-public is what lets it eliminate them.

What Trie Autocomplete actually is

A trie stores a set of strings as a tree where each edge carries one character and every node is the shared prefix of everything beneath it. Walking m characters lands you on the subtree of all completions, so prefix lookup costs O(m) regardless of dictionary size; enumerating k suggestions then costs O(k) plus the length of what you emit. Engineers reach for it for search-box typeahead, command palettes, IP/route tables and spell correction: anywhere the query is a prefix and the answer set must be produced per keystroke. If the dictionary is static and read-only, a sorted array plus binary search is usually smaller and faster.

Trie Autocomplete in Swift: what you actually reach for

The Swift standard library has no trie. The node is a final class holding var children: [Character: TrieNode]. Character is an extended grapheme cluster, which is the right unit for user-visible typing but not for byte-level work; String also exposes unicodeScalars and utf8 views if you want a scalar or byte trie instead. Character and String are both Comparable, so children.keys.sorted() gives ordered suggestions. swift-collections (import Collections) adds OrderedDictionary if you want insertion-ordered children without a sort.

Swift implementation

The node is declared final class, never struct, and final is not optional style: it lets the optimizer devirtualize property access. Descent uses guard let next = node.children[ch] else { return [] } rather than force unwrapping. The public API takes String and returns [String], with the prefix parameter unlabelled (_ prefix: String) to read as complete("ca"). Reviewers ask you to state, in a comment, whether the trie keys on Character or on Unicode.Scalar, because the two behave differently on composed text.
swift
final class TrieNode {
    var children: [Character: TrieNode] = [:]
    var isWord = false
}

final class Trie {
    private let root = TrieNode()

    func insert(_ word: String) {
        var node = root
        for ch in word {
            if let next = node.children[ch] {
                node = next
            } else {
                let next = TrieNode()
                node.children[ch] = next
                node = next
            }
        }
        node.isWord = true
    }

    func complete(_ prefix: String, limit: Int = 10) -> [String] {
        var node = root
        for ch in prefix {
            guard let next = node.children[ch] else { return [] }
            node = next
        }
        var out: [String] = []
        var stack: [(node: TrieNode, path: String)] = [(node, prefix)]
        while out.count < limit, let top = stack.popLast() {
            if top.node.isWord {
                out.append(top.path)
            }
            for ch in top.node.children.keys.sorted().reversed() {
                if let child = top.node.children[ch] {
                    stack.append((child, top.path + String(ch)))
                }
            }
        }
        return out
    }
}

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 Free

The Swift-specific trap

Declare the node as a struct and the algorithm quietly stops working, but not for the reason people first guess. node.children[ch]?.isWord = true does write back, because optional-chaining assignment goes through the Dictionary subscript setter. What breaks is the descent itself: var node = root copies the entire struct, so from the second character onward you are mutating a detached copy and the tree never sees the insert. Rebuilding the chain on the way back up instead copies each subtree under copy-on-write, which is correct but turns an O(m) insert into something only the profiler catches. The node must be a final class. Related: Character is a grapheme cluster, so "e\u{301}" and "é" compare equal as Characters and land on the same edge, while a unicodeScalars trie stores them at different depths.

Performance in Swift, beyond the O(m)

Every node = next in the descent is a retain/release pair unless the optimizer proves the lifetime, so ARC traffic, not hashing, is usually the top of the profile in a whole-module-optimisation build; marking the class final and the properties non-public is what lets it eliminate them. String(ch) and path + String(ch) each allocate. Hashing a Character means hashing its scalars, more work than a UInt8 key, so a utf8-keyed trie is materially faster. Never call String.count in a loop bound: it walks grapheme breaks, O(n) every time. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie Autocomplete between languages.

Real-World Applications

Trie Autocomplete applies wherever its problem shape appears in your own code. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie Autocomplete helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie Autocomplete appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie Autocomplete over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie Autocomplete to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

Frequently Asked Questions

Which Swift type or library should I use for Trie Autocomplete?

The Swift standard library has no trie. The node is a final class holding var children: [Character: TrieNode]. Character is an extended grapheme cluster, which is the right unit for user-visible typing but not for byte-level work; String also exposes unicodeScalars and utf8 views if you want a scalar or byte trie instead. Character and String are both Comparable, so children.keys.sorted() gives ordered suggestions. swift-collections (import Collections) adds OrderedDictionary if you want insertion-ordered children without a sort.

What is the most common Swift mistake when implementing Trie Autocomplete?

Declare the node as a struct and the algorithm quietly stops working, but not for the reason people first guess. node.children[ch]?.isWord = true does write back, because optional-chaining assignment goes through the Dictionary subscript setter. What breaks is the descent itself: var node = root copies the entire struct, so from the second character onward you are mutating a detached copy and the tree never sees the insert. Rebuilding the chain on the way back up instead copies each subtree under copy-on-write, which is correct but turns an O(m) insert into something only the profiler catches. The node must be a final class. Related: Character is a grapheme cluster, so "e\u{301}" and "é" compare equal as Characters and land on the same edge, while a unicodeScalars trie stores them at different depths.

How does Trie Autocomplete actually perform in Swift?

Every node = next in the descent is a retain/release pair unless the optimizer proves the lifetime, so ARC traffic, not hashing, is usually the top of the profile in a whole-module-optimisation build; marking the class final and the properties non-public is what lets it eliminate them. String(ch) and path + String(ch) each allocate. Hashing a Character means hashing its scalars, more work than a UInt8 key, so a utf8-keyed trie is materially faster. Never call String.count in a loop bound: it walks grapheme breaks, O(n) every time. Time complexity is O(m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Devin free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.