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

Search Engine Implementation in Swift

19 min readadvanced
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

  • ✓Search Engine runs in O(n log n) time and O(n) space, in Swift as in every other language.
  • ✓[String: [Posting]] with the subscript(_:default:) form for accumulation. Tokenizing has three real options: Foundation's enumerateSubstrings(in:options:) with .byWords, the NaturalLanguage framework's NLTokenizer(unit: .word) which is locale-aware and segments CJK, and Swift's own Regex literals.
  • ✓Reviewers demand postings[term, default: []].append(p) over the read-modify-write triple, reserveCapacity before a known-size fill, and Substring rather than String until a value is actually stored.
  • ✓The Swift trap: Array is copy-on-write and the naive accumulation defeats it. `var list = postings[term] ??
  • ✓Every String key is ARC traffic unless it fits the small-string form: a native Swift string of 15 UTF-8 bytes or fewer lives inline in the 16-byte value with no allocation and no retain/release, so short tokens are dramatically cheaper than long ones and a stemmer pays for itself twice.

What Search Engine actually is

A search engine is an inverted index plus a ranker. Indexing tokenizes each document, normalizes the tokens, and appends (docId, termFrequency) to a postings list per term; building or merging those sorted runs is the O(n log n). Querying pulls one postings list per query term, intersects or unions them, scores each candidate with something like BM25, and keeps the top k in a bounded heap. You reach for it the moment LIKE '%x%' stops finishing and users start expecting relevance, not just matches.

Search Engine in Swift: what you actually reach for

[String: [Posting]] with the subscript(_:default:) form for accumulation. Tokenizing has three real options: Foundation's enumerateSubstrings(in:options:) with .byWords, the NaturalLanguage framework's NLTokenizer(unit: .word) which is locale-aware and segments CJK, and Swift's own Regex literals. There is no heap in the standard library -- the swift-collections package supplies Heap, and swift-algorithms supplies max(count:sortedBy:) for a partial top-k without a full sort. Foundation provides log and pow for the BM25 arithmetic.

Swift implementation

Reviewers demand postings[term, default: []].append(p) over the read-modify-write triple, reserveCapacity before a known-size fill, and Substring rather than String until a value is actually stored. Posting is a struct; only the index itself is a final class. Optional postings are unwrapped with guard let, never force-unwrapped, because a missing term is the normal case in a query. Reaching for NSString bridging in the tokenizer gets flagged in favour of the native String APIs.
swift
import Foundation

struct Result { let doc: Int; let score: Double }
struct Posting { let doc: Int; let tf: Int }

final class InvertedIndex {
    private var postings: [String: [Posting]] = [:]
    private var lengths: [Int: Int] = [:]

    func add(doc: Int, text: String) {
        let lower = text.lowercased()
        var tf: [String: Int] = [:]
        lower.enumerateSubstrings(in: lower.startIndex..<lower.endIndex,
                                  options: .byWords) { sub, _, _, _ in
            if let s = sub { tf[s, default: 0] += 1 }
        }
        lengths[doc] = tf.values.reduce(0, +)
        postings.reserveCapacity(postings.count + tf.count)
        for (term, n) in tf {
            // _modify accessor: appends in place, refcount stays 1, no CoW copy
            postings[term, default: []].append(Posting(doc: doc, tf: n))
        }
    }

    func search(_ query: String, k: Int = 10) -> [Result] {
        let n = Double(lengths.count)
        var scores: [Int: Double] = [:]
        for term in query.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }) {
            guard let list = postings[String(term)] else { continue }
            let df = Double(list.count)
            let idf = log(1 + (n - df + 0.5) / (df + 0.5))
            for p in list {
                let tf = Double(p.tf)
                scores[p.doc, default: 0] += idf * tf / (tf + 1.2)
            }
        }
        let ranked = scores.map { Result(doc: $0.key, score: $0.value) }
                           .sorted { $0.score > $1.score }
        return Array(ranked.prefix(k))
    }
}

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

Array is copy-on-write and the naive accumulation defeats it. `var list = postings[term] ?? []; list.append(p); postings[term] = list` puts the buffer's reference count at 2 the instant `list` binds, so append copies the entire postings list -- for every token, turning an O(n) build into O(n squared) on the hottest terms. `postings[term, default: []].append(p)` goes through the dictionary's _modify accessor and mutates the same buffer with refcount 1. The two lines look interchangeable in review; one indexes a corpus in seconds and the other never finishes.

Performance in Swift, beyond the O(n log n)

Every String key is ARC traffic unless it fits the small-string form: a native Swift string of 15 UTF-8 bytes or fewer lives inline in the 16-byte value with no allocation and no retain/release, so short tokens are dramatically cheaper than long ones and a stemmer pays for itself twice. A Substring keeps its parent document's whole storage alive, so materialize String(sub) on the insert path. Dictionary hashing is seeded per process, so iteration order changes between runs and any golden-file test of the index will flap. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Search Engine between languages.

Real-World Applications

Search Engine 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 Search Engine helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Search Engine appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Search Engine 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 Search Engine 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 Search Engine?

[String: [Posting]] with the subscript(_:default:) form for accumulation. Tokenizing has three real options: Foundation's enumerateSubstrings(in:options:) with .byWords, the NaturalLanguage framework's NLTokenizer(unit: .word) which is locale-aware and segments CJK, and Swift's own Regex literals. There is no heap in the standard library -- the swift-collections package supplies Heap, and swift-algorithms supplies max(count:sortedBy:) for a partial top-k without a full sort. Foundation provides log and pow for the BM25 arithmetic.

What is the most common Swift mistake when implementing Search Engine?

Array is copy-on-write and the naive accumulation defeats it. `var list = postings[term] ?? []; list.append(p); postings[term] = list` puts the buffer's reference count at 2 the instant `list` binds, so append copies the entire postings list -- for every token, turning an O(n) build into O(n squared) on the hottest terms. `postings[term, default: []].append(p)` goes through the dictionary's _modify accessor and mutates the same buffer with refcount 1. The two lines look interchangeable in review; one indexes a corpus in seconds and the other never finishes.

How does Search Engine actually perform in Swift?

Every String key is ARC traffic unless it fits the small-string form: a native Swift string of 15 UTF-8 bytes or fewer lives inline in the 16-byte value with no allocation and no retain/release, so short tokens are dramatically cheaper than long ones and a stemmer pays for itself twice. A Substring keeps its parent document's whole storage alive, so materialize String(sub) on the insert path. Dictionary hashing is seeded per process, so iteration order changes between runs and any golden-file test of the index will flap. Time complexity is O(n log n) and space is O(n).

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

Before paying for Devin, check its student and free-tier options 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.