Keep Search Highlights Attached To The Original Text
A reader searches for cafe. Your list correctly finds Café, but the highlighter finds nothing. Another result highlights the wrong character because the code searched a lowercased copy and applied its offsets to the original.
The search field has quietly become a second text editor.
Let’s give filtering and highlighting the same match result. We’ll search the original title, preserve its spelling and spacing, and apply color to complete characters in one AttributedString.
This is for a modest, already-loaded list of titles. Foundation supplies the search behavior; we add a consistent policy for displaying its matches.
Separate finding a match from drawing it
The Stack Overflow discussion about highlighting SwiftUI text already has an accepted answer and newer AttributedString examples. It also illustrates a tempting shortcut: search lowercased text, then reuse the resulting offsets in the original text.
That shortcut assumes case conversion preserves positions. For example, İX has two UTF-16 code units; its default lowercased form has three. An offset describing x in the transformed string does not describe X in the original. Converting that offset to NSRange still leaves it attached to the wrong string.
Alexander Weiss’s highlighted-text component usefully separates finding ranges from drawing them with TextRenderer. We will keep that separation, then add system search semantics, whole-character boundaries and a single decision for both filtering and styling. Plain attributed colors are enough for this example; our TextRenderer article covers custom drawing.
Apple’s WWDC26 search-design session emphasizes relevant results and a clear empty state. The less visible part is making the highlighted portion explain why a result appeared.
Find ranges in the original title
Foundation’s localizedStandardRange(of:) performs a locale-aware, case- and diacritic-insensitive search. Apple’s multilingual-app session recommends it for user-facing search and explains the broader spelling and cross-script numeral matching added in iOS 18.
Use the system behavior instead of constructing a lowercased or accent-stripped shadow string. Foundation owns which spellings match; our code owns which original characters receive the highlight.
The two Swift blocks below belong in one file. The downloadable sample includes the complete view and verification fixtures. It uses Swift 6.4 and targets iOS 18 or macOS 15 and later.
import Foundation
import SwiftUI
nonisolated struct TitleMatch {
let source: String
let ranges: [Range<String.Index>]
init(_ source: String, query: String) {
self.source = source
var matches: [Range<String.Index>] = []
var start = source.startIndex
if !query.isEmpty {
while start < source.endIndex,
let found = source[start...]
.localizedStandardRange(of: query),
!found.isEmpty {
// Expand to boundaries reached by walking Swift Characters.
var lower = start
var upper = source.index(after: lower)
while upper <= found.lowerBound {
lower = upper
upper = source.index(after: upper)
}
while upper < found.upperBound {
upper = source.index(after: upper)
}
matches.append(lower..<upper)
start = upper
}
}
ranges = matches
}
var hasMatch: Bool { !ranges.isEmpty }
var highlightedText: AttributedString {
var result = AttributedString(source)
for range in ranges {
guard let attributedRange = Range<AttributedString.Index>(
range, in: result
) else {
preconditionFailure("A match must belong to its original text")
}
result[attributedRange].backgroundColor = .yellow
result[attributedRange].foregroundColor = .black
}
return result
}
}
Searching source[start...] uses a substring of the original. Its indices remain in the original string’s coordinate space. We never reconstruct a title by splitting on spaces or by inserting the query between fragments, so the original case, accents and whitespace survive.
The loop moves forward after every highlighted span. An empty query produces no highlights; the defensive empty-match check prevents a zero-length result from leaving the loop in place. Matches are nonoverlapping: ana in banana highlights the first occurrence.
There is one deliberate display choice: expand each match to complete Swift Character boundaries. Starting at the previous span’s end, the two short loops walk those boundaries until they enclose the match. A match for an emoji component can therefore highlight the whole emoji, including its modifiers and joined components. We then resume after that expanded span, so this is not a count of every overlapping substring.
Why walk the string instead of calling Foundation’s composed-sequence helper? Their boundaries can differ. In our checks, Foundation’s helper left the zero-width non-joiner outside a matched Devanagari cluster; Swift kept it inside the same Character. Walking the original string makes our display rule explicit. The highlight includes that invisible character too—it still has a job.
The range conversion happens against an attributed copy of the same, unchanged source. Only attributes change. The precondition catches an unexpected conversion failure; the value keeps the source and its ranges together. A successful conversion alone cannot prove that an index came from the right string. If the underlying text changes, create a new TitleMatch rather than retaining its indices for the edited string.
Let the same result decide which rows appear
The example keeps each title’s persistent identity separate from its text. Duplicate titles are allowed; duplicate row identities are not.
@MainActor
struct TitleSearchDemo: View {
private struct Entry: Identifiable {
let id: Int
let title: String
}
private struct Row: Identifiable {
let id: Int
let match: TitleMatch
}
@State private var query = ""
private let entries = [
Entry(id: 1, title: "Café notes — CAFÉ ideas"),
Entry(id: 2, title: "A guide to Straße and Strasse"),
Entry(id: 3, title: "👩🏽💻 Developer handbook"),
Entry(id: 4, title: "Chapter १२३"),
Entry(id: 5, title: "क्षितिज — reading notes"),
Entry(id: 6, title: "مكتبة الكتب"),
Entry(id: 7, title: "A guide to Straße and Strasse")
]
private var results: [Row] {
entries.compactMap { entry in
let match = TitleMatch(entry.title, query: query)
guard query.isEmpty || match.hasMatch else { return nil }
return Row(id: entry.id, match: match)
}
}
var body: some View {
let rows = results
NavigationStack {
List(rows) { row in
Text(row.match.highlightedText)
.textSelection(.enabled)
.accessibilityLabel(Text(verbatim: row.match.source))
}
.overlay {
if rows.isEmpty {
ContentUnavailableView.search(text: query)
}
}
.navigationTitle("Library")
.searchable(text: $query, prompt: "Search titles")
}
}
}
There is no separate contains check with a different comparison policy. A nonempty query includes a row exactly when its TitleMatch found a range. Clearing the query restores all rows without manufacturing empty highlights.
The sample treats the query as user text, not a regular expression or Markdown. It does not trim whitespace or turn punctuation into a search language. If your product needs those rules, apply them once before constructing the results, and make the resulting behavior clear in the interface.
localizedStandardRange uses Foundation’s current locale. Passing a different locale through SwiftUI’s environment alone does not configure this Foundation method. An app with an explicit per-search locale needs a separately defined matching policy; don’t claim that a hand-picked pair of comparison options exactly reproduces every system search rule.
For a database-backed catalog, use the index’s own matching information where available. Highlighting local substrings cannot explain a server result that matched only a synonym or hidden field. Our GRDB search example covers an indexed path, and stale-result ownership matters once matching becomes asynchronous.
Change color without changing the font
The highlighted characters use a yellow background and black foreground. The surrounding text keeps its normal adaptive color and font. The whole title remains one Text value, with no artificial spaces between styled fragments.
Apple demonstrates an important reason for avoiding font-weight changes in multilingual search results: changing the font inside connected scripts can break how letters and marks join. Attributed color gives emphasis without intentionally switching fonts. Whole-character boundaries are an additional display choice, not a substitute for testing your supported scripts.
The highlight is supplemental. A result retains its complete readable title, and the accessibility label uses that original title rather than announcing a collection of colored fragments. Keep semantic text sizing and allow wrapping. Test your own colors, layout and languages with large text, increased contrast and VoiceOver; a successful range test cannot certify those experiences.
Test the strings that make shortcuts fail
Useful fixtures include:
| Input and query | What to verify |
|---|---|
Café CAFÉ café searched with cafe | Repeated matches, including a decomposed accent; original UTF-8 bytes remain unchanged. |
Straße Strasse searched with STRASSE | Equivalent matches can occupy different lengths in the original. |
İX searched with x | Highlight X using its original position, not the offset from a lowercased copy. |
👩🏽💻 searched with 👩 | Expand the highlight to the complete composed character. |
Chapter १२३ searched with 123 | Exercise the current runtime’s cross-script numeral matching. |
| A Devanagari cluster containing a zero-width non-joiner; a CRLF line ending | Expanded spans must end on Swift Character boundaries, including invisible characters. |
| Empty query, missing query, punctuation and repeated spaces | No loop, no accidental pattern syntax, and no rewritten title. |
These are expected observations on the tested runtime, not a promise that linguistic matching rules never evolve. Apple explicitly reserves the ability to refine its standard search options. Keep fixtures representative of the languages your app supports.
The exact examples were compiled with Xcode 27.2 and Swift 6.4.2, with warnings treated as errors, in ordinary and MainActor-default isolation. The matching checks ran on macOS 27.2 and an iOS 27.2 iPhone simulator. Native UI tests covered search, clearing, duplicate titles, no results and accessibility text sizing; light/dark screenshots also checked the connected-script and emoji examples. The iOS 18/macOS 15 targets were compile-checked, not run on those oldest OS versions. Physical devices and a manual VoiceOver session remain outside this verification.
The payoff is a small, consistent search boundary: the ranges that admit a result are the ranges that explain it, and the stored title makes the round trip intact.