Text 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
- ✓Text Search Engine runs in O(n log n) time and O(n) space, in Swift as in every other language.
- ✓The corpus goes through String.UTF8View: Array(text.utf8) gives [UInt8], and ContiguousArray<Int32> holds the offsets with a guaranteed contiguous buffer.
- ✓There is no Int subscript on String and a reviewer will not accept one being faked with index(startIndex, offsetBy:) inside a loop, because that walk is O(k) every time.
- ✓The Swift trap: Swift String comparison is canonical, not code-unit. "caf\u{e9}" and the same word written with a combining acute (U+0301) are == in Swift, they hash identically, and they are interchangeable as Dictionary keys.
- ✓A comparator that touches String pays ARC retain/release traffic on every comparison, which is why the index is built over [UInt8] and ContiguousArray<Int32> value types instead.
What Text Search Engine actually is
Text Search Engine in Swift: what you actually reach for
Swift implementation
import Foundation
struct SuffixIndex {
private let bytes: [UInt8]
private let sa: [Int32]
init(_ corpus: String) {
// one normalisation form for the whole engine, fixed at ingest
bytes = Array(corpus.precomposedStringWithCanonicalMapping.utf8)
sa = SuffixIndex.build(bytes)
}
private static func build(_ t: [UInt8]) -> [Int32] {
let n = t.count
var sa = Array(Int32(0)..<Int32(n))
var rank = t.map { Int32($0) }
var nxt = [Int32](repeating: 0, count: n)
var k = 1
while k < n {
func key(_ i: Int32) -> (Int32, Int32) {
let i = Int(i)
return (rank[i], i + k < n ? rank[i + k] : -1)
}
sa.sort { key($0) < key($1) }
nxt[Int(sa[0])] = 0
for w in 1..<n {
nxt[Int(sa[w])] = nxt[Int(sa[w - 1])] + (key(sa[w - 1]) == key(sa[w]) ? 0 : 1)
}
rank = nxt
if rank[Int(sa[n - 1])] == Int32(n - 1) { break }
k <<= 1
}
return sa
}
/// Position in suffix-array order of the first suffix >= pattern.
func lowerBound(_ pattern: String) -> Int {
let p = Array(pattern.precomposedStringWithCanonicalMapping.utf8)
var lo = 0, hi = sa.count
while lo < hi {
let m = (lo + hi) / 2
let s = bytes[Int(sa[m])...].prefix(p.count)
if s.lexicographicallyPrecedes(p) { lo = m + 1 } else { hi = m }
}
return lo
}
}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 Text Search Engine?
The corpus goes through String.UTF8View: Array(text.utf8) gives [UInt8], and ContiguousArray<Int32> holds the offsets with a guaranteed contiguous buffer. Array.sort(by:) has been a modified timsort since Swift 5: adaptive, so the nearly-sorted sa that every doubling round after the first hands it costs close to O(n), but it allocates an O(n) temporary buffer on every call, and it is still explicitly not documented as stable, so never lean on tie order. There is no binary search in the standard library at all: you either hand-roll the lower bound or pull swift-algorithms, Apple's own package, for partitioningIndex(where:). Foundation supplies precomposedStringWithCanonicalMapping and decomposedStringWithCanonicalMapping for normalization, plus NSRegularExpression. On Apple platforms NaturalLanguage's NLTokenizer segments words in scripts that have no spaces.
What is the most common Swift mistake when implementing Text Search Engine?
Swift String comparison is canonical, not code-unit. "caf\u{e9}" and the same word written with a combining acute (U+0301) are == in Swift, they hash identically, and they are interchangeable as Dictionary keys. Your suffix array is built over utf8 bytes, which are not equal at all. So Swift's own text.contains(query) returns true while index.lookup(query) returns nothing, on the same two values, in the same process. There are genuinely two equalities inside one type. Normalize both corpus and pattern to the same form at the boundary; nothing further down can rescue it.
How does Text Search Engine actually perform in Swift?
A comparator that touches String pays ARC retain/release traffic on every comparison, which is why the index is built over [UInt8] and ContiguousArray<Int32> value types instead. Even then, every Array mutation carries a bounds check and a uniqueness check (isKnownUniquelyReferenced) for copy-on-write; withUnsafeMutableBufferPointer removes both from the inner loop and is the single largest win here. The small-string optimisation keeps up to 15 UTF-8 bytes inline with no allocation, so token-level work stays cheap. On Apple platforms a String bridged from NSString can make .utf8 a lazily transcoding view rather than a straight read. 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 GitHub Copilot, 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.