Search Engine 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
- ✓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
Search Engine in Swift: what you actually reach for
Swift implementation
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 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 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).
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.