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

Text 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

  • ✓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

An in-memory full-text index that answers "which documents contain this substring" without rescanning the corpus. Concatenate every document into one byte buffer, sort all n suffixes by prefix doubling, and keep two things: the suffix array of offsets and the document-start boundaries. Written the way every snippet here writes it, with a comparison sort inside each of the log n rounds, that build is O(n log^2 n); radix-sorting each round brings it to O(n log n), and SA-IS, which is what Go's index/suffixarray uses, is linear. The index itself is O(n) space. Any pattern of length m is then a contiguous range of the suffix array, found by two binary searches in O(m log n). You reach for this instead of an inverted index when queries are infix, code-like, or in a language you cannot reliably tokenize.

Text Search Engine in Swift: what you actually reach for

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.

Swift implementation

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. Work over text.utf8 or a materialised [UInt8]; keep String.Index only at the API edge where you hand ranges back to a caller. Normalization is chosen once at ingest and applied to both corpus and query, written down as a stated invariant. ContiguousArray for the index once it is big enough for the buffer guarantee to matter, and withUnsafeBufferPointer around the doubling loop when the bounds checks show up in a profile; the plain [Int32] in the sketch below is the honest starting point, not the finished index.
swift
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 Free

The Swift-specific 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. 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.

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

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. 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 Text Search Engine between languages.

Real-World Applications

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

Interview Tips & Practice

Text 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 Text 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 Text 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 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).

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 GitHub Copilot, 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.