Sample CodeiOS, iPadOS, Mac CatalystReviewed 2026-11-01View on Apple Developer

Searching indexed content with natural language

At a glance

Item Summary
Purpose Give a Foundation Models language-model session a SpotlightSearchTool so it can query the app’s Core Spotlight index and answer natural-language questions about hiking trails.
App architecture One SwiftUI app target. ContentView owns an @Observable SessionViewModel in @State. The view model builds a fresh SpotlightSearchTool and LanguageModelSession per search. A SpotlightIndexer singleton owns the named CSSearchableIndex, indexes the bundled plist, and acts as the index delegate that the tool also receives.
Main patterns Model-View-ViewModel, @Observable state, a CSSearchableIndexDelegate callback object, and a static let shared singleton with a private initializer.
Project style Six flat Swift files in LLMSearchUsingCoreSpotlightApp/, one role per file: app entry, root view and row subviews, view model (Session.swift), detail view, indexer, and an Error display extension.
Execution model The target sets SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, so undecorated types are main-actor isolated. Index-delegate methods are nonisolated and re-enter with Task { @MainActor in ... }. The view model retains and cancels one search-results listener task.
State/event model SwiftUI reads @Observable view-model properties; the search field binds to viewModel.prompt. Tool results arrive as an async sequence (tool.searchResults) and model text as session.streamResponse(to:).
Key frameworks/packages SwiftUI, CoreSpotlight, FoundationModels, Observation, UniformTypeIdentifiers, os. The project declares no Swift package.

Project structure

LLMSearchUsingCoreSpotlight.xcodeproj/   one app target, no Swift packages
LLMSearchUsingCoreSpotlight.entitlements empty entitlements dictionary
LLMSearchUsingCoreSpotlightApp/
├── LLMSearchUsingCoreSpotlightApp.swift @main App, WindowGroup { ContentView() }
├── ContentView.swift                    root view; SummarySection, SearchingView, TrailImageView, TrailRowView
├── Session.swift                        @Observable SessionViewModel (tool, session, streaming)
├── Indexer.swift                        SpotlightIndexer singleton + private TrailData decoding model
├── TrailDetailView.swift                read-only detail view over CSSearchableItem attributes
├── Error+DisplayMessage.swift           Error.displayMessage for model errors
└── SampleData.plist                     bundled trail records
Localizable.xcstrings

Structure observations

  • The file name Session.swift holds SessionViewModel, not a session type (LLMSearchUsingCoreSpotlightApp/Session.swift:16). The LanguageModelSession itself is a local value created per search.
  • CSSearchableItem is the only model type that reaches views. TrailData is a private decoding struct inside Indexer.swift (LLMSearchUsingCoreSpotlightApp/Indexer.swift:15) and never leaves that file.
  • The entitlements file is an empty dictionary (LLMSearchUsingCoreSpotlight.entitlements:4). The view model’s comment describes requesting Private Cloud Compute access separately and swapping one initializer line (LLMSearchUsingCoreSpotlightApp/Session.swift:27).

Platform boundary

The DocC record lists iOS, iPadOS, and Mac Catalyst. The app target sets SDKROOT = iphoneos and TARGETED_DEVICE_FAMILY = "1,2" with no Mac Catalyst setting (LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:311, LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:318), so the source itself shows only an iPhone and iPad build. The project deployment target is iOS 27.0 (LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:211).

Overall architecture

Reference code

LLMSearchUsingCoreSpotlightApp/Session.swift:140 — the tool and session factories

    private func makeSpotlightTool() -> SpotlightSearchTool {
        SpotlightSearchTool(
            configuration: .init(
                sources: [
                    .coreSpotlight(
                        .init(
                            searchableIndexDelegate: SpotlightIndexer.shared,
                            fetchAttributes: Self.fetchAttributes
                        )
                    )
                ],
                guide: isOnDevice ? .focused() : .complete
            )
        )
    }

    private func makeSession(tool: SpotlightSearchTool) -> LanguageModelSession {
        LanguageModelSession(
            model: foundationModel,
            tools: [tool],
            instructions: instructions
        )
    }

Interpretation

Observed: there are two independent paths into Core Spotlight. On launch, ContentView’s .task asks SpotlightIndexer.shared to build items and index them if the index has no client state (LLMSearchUsingCoreSpotlightApp/ContentView.swift:71). On search, the view model hands the same indexer to SpotlightSearchTool as its searchableIndexDelegate, and the language model, not app code, issues the Spotlight queries. The tool’s guide is .focused() for the on-device SystemLanguageModel and .complete otherwise (LLMSearchUsingCoreSpotlightApp/Session.swift:151).

Observed: the view model’s instructions string describes every indexed attribute and how to search them (LLMSearchUsingCoreSpotlightApp/Session.swift:41). Inference: the schema that makeAttributeSet(from:) writes and the prose the model reads are maintained by hand in two files, so adding an attribute means editing both.

Ownership and state

Ownership evidence

LLMSearchUsingCoreSpotlightApp/Session.swift:16 — view-model state and retained task

@Observable
final class SessionViewModel {

    var isGenerating = false
    var hasSearched = false
    var results: [CSSearchableItem] = []
    var response = ""
    var prompt = ""
    var error: String?

    private var searchResultsTask: Task<Void, Never>?
    // ...
    let foundationModel = SystemLanguageModel()
    // ...
}

LLMSearchUsingCoreSpotlightApp/Indexer.swift:34 — the indexer singleton

final class SpotlightIndexer: NSObject, CSSearchableIndexDelegate {

    static let shared = SpotlightIndexer()

    let index = CSSearchableIndex(name: "TrailSearchSample")

    private(set) var imageNames: [String: String] = [:]
    // ...
    private override init() {
        super.init()
        index.indexDelegate = self
    }
    // ...
}
Owner Object or state Relationship Mutation authority
ContentView SessionViewModel Creates it in @State private var viewModel (LLMSearchUsingCoreSpotlightApp/ContentView.swift:13) View model mutates its own state; the view writes hasSearched and binds prompt (LLMSearchUsingCoreSpotlightApp/ContentView.swift:48, LLMSearchUsingCoreSpotlightApp/ContentView.swift:51)
ContentView allTrails browse list @State private var, filled in .task from createSearchableItems() (LLMSearchUsingCoreSpotlightApp/ContentView.swift:72) ContentView
SessionViewModel isGenerating, hasSearched, results, response, prompt, error Implicitly internal observable properties SessionViewModel (run(), reset()), plus the view’s binding and hasSearched write
SessionViewModel SpotlightSearchTool, LanguageModelSession Local values created in run(); not stored (LLMSearchUsingCoreSpotlightApp/Session.swift:107) None after creation
SessionViewModel searchResultsTask private var, replaced each run and cancelled by reset()/run() (LLMSearchUsingCoreSpotlightApp/Session.swift:25) SessionViewModel
SpotlightIndexer CSSearchableIndex named TrailSearchSample let index, created once by the singleton (LLMSearchUsingCoreSpotlightApp/Indexer.swift:38) Indexer methods only
SpotlightIndexer imageNames lookup private(set), rebuilt by createSearchableItems() (LLMSearchUsingCoreSpotlightApp/Indexer.swift:141) SpotlightIndexer
TrailDetailView, TrailRowView, SummarySection Item, image name, response text let/var inputs passed by the parent Read-only

Observed: the per-search tool and session are never stored, so each query starts with fresh model context, matching the doc comment on run() (LLMSearchUsingCoreSpotlightApp/Session.swift:97). ContentView merges the two result sources in enrichedResults, replacing each tool-returned item with the locally built item that has the same identifier (LLMSearchUsingCoreSpotlightApp/ContentView.swift:79).

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Default isolation SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, SWIFT_APPROACHABLE_CONCURRENCY = YES, Swift 6 Undecorated declarations, including SessionViewModel and SpotlightIndexer, are main-actor isolated by the build setting rather than by annotation LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:313, LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:314, LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:317
UI-created task .onSubmit(of: .search) { Task { ... await viewModel.run() } } Plain Task from a main-actor view; not stored, so nothing cancels a running stream when another search is submitted LLMSearchUsingCoreSpotlightApp/ContentView.swift:50
SwiftUI-managed task .task { ... await SpotlightIndexer.shared.indexIfNeeded() } SwiftUI ties the launch-indexing task to the view’s lifetime LLMSearchUsingCoreSpotlightApp/ContentView.swift:71
Retained, cancellable task searchResultsTask = listenForSearchResults(from: tool); searchResultsTask?.cancel() in run() and reset() The only stored task; one listener per search, replaced on the next search LLMSearchUsingCoreSpotlightApp/Session.swift:89, LLMSearchUsingCoreSpotlightApp/Session.swift:101, LLMSearchUsingCoreSpotlightApp/Session.swift:109
Main-actor listener Task { @MainActor in for await reply in tool.searchResults { ... } } Appends de-duplicated items to results on the main actor LLMSearchUsingCoreSpotlightApp/Session.swift:165, LLMSearchUsingCoreSpotlightApp/Session.swift:182
Streaming for try await chunk in session.streamResponse(to: prompt) Each chunk replaces response; errors map to displayMessage LLMSearchUsingCoreSpotlightApp/Session.swift:189
Callback to async withCheckedContinuation around fetchLastClientState Bridges the completion handler into indexIfNeeded(); client state gates first-launch indexing LLMSearchUsingCoreSpotlightApp/Indexer.swift:63
Delegate re-entry nonisolated func searchableIndex(...) and searchableItems(forIdentifiers:...) creating Task { @MainActor in ... } Delegate calls arrive outside the main actor contract and hop back before touching indexer state LLMSearchUsingCoreSpotlightApp/Indexer.swift:92, LLMSearchUsingCoreSpotlightApp/Indexer.swift:96, LLMSearchUsingCoreSpotlightApp/Indexer.swift:124
Acknowledgement timing acknowledgementHandler() after starting the task The reindex delegate methods acknowledge immediately; they do not wait for the reindex task to finish LLMSearchUsingCoreSpotlightApp/Indexer.swift:99, LLMSearchUsingCoreSpotlightApp/Indexer.swift:120
Transfer contract searchableItemsHandler: @escaping @Sendable The handler is called from inside the main-actor task; @Sendable alone does not synchronize state LLMSearchUsingCoreSpotlightApp/Indexer.swift:123

Reference code

LLMSearchUsingCoreSpotlightApp/Indexer.swift:92 — nonisolated delegate callback hopping to the main actor

    nonisolated func searchableIndex(
        _ searchableIndex: CSSearchableIndex,
        reindexAllSearchableItemsWithAcknowledgementHandler acknowledgementHandler: @escaping () -> Void
    ) {
        Task { @MainActor in
            await indexAllItems()
        }
        acknowledgementHandler()
    }

Interpretation: imageNames and index are protected by main-actor isolation, which the build setting supplies, not by a lock. Not established by source: which thread or queue Core Spotlight and SpotlightSearchTool use to call the delegate, or where the language model executes.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Model-to-view state @Observable SessionViewModel read by ContentView.body Body branches on hasSearched, results, isGenerating, response, error LLMSearchUsingCoreSpotlightApp/Session.swift:15, LLMSearchUsingCoreSpotlightApp/ContentView.swift:19
View-to-model input .searchable(text: $viewModel.prompt) and .onChange(of: viewModel.prompt) Binding writes the prompt; clearing it calls reset() LLMSearchUsingCoreSpotlightApp/ContentView.swift:48, LLMSearchUsingCoreSpotlightApp/ContentView.swift:55
Tool-to-model results tool.searchResults async sequence Items, scored items, and grouped items are flattened; counts, tables, statistics, and text replies are skipped LLMSearchUsingCoreSpotlightApp/Session.swift:167
Navigation NavigationLink(value: item.uniqueIdentifier) and .navigationDestination(for: String.self) Identifiers, not items, travel through navigation; the destination looks the item up again LLMSearchUsingCoreSpotlightApp/ContentView.swift:60
Error presentation extension Error { var displayMessage } Maps SystemLanguageModel.Error and LanguageModelError cases to short strings LLMSearchUsingCoreSpotlightApp/Error+DisplayMessage.swift:13
Framework import FoundationModels, CoreSpotlight, Observation View-model compilation dependencies LLMSearchUsingCoreSpotlightApp/Session.swift:9, LLMSearchUsingCoreSpotlightApp/Session.swift:10, LLMSearchUsingCoreSpotlightApp/Session.swift:11
Framework import UniformTypeIdentifiers, os Indexer: .text content type and Logger LLMSearchUsingCoreSpotlightApp/Indexer.swift:10, LLMSearchUsingCoreSpotlightApp/Indexer.swift:11
Framework import SwiftUI App and views LLMSearchUsingCoreSpotlightApp/LLMSearchUsingCoreSpotlightApp.swift:8
Package declaration None The project file declares no Swift package LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj:311

The source uses no Combine, so there is no receive(on:) or subscribe(on:) scheduling.

Class and protocol design

Reference code

LLMSearchUsingCoreSpotlightApp/Indexer.swift:42 — custom attribute key shared by indexer and view model

final class SpotlightIndexer: NSObject, CSSearchableIndexDelegate {
    // ...
    static let distanceAttributeKey: CSCustomAttributeKey? = CSCustomAttributeKey(
        keyName: "distance",
        searchable: true,
        searchableByDefault: true,
        unique: false,
        multiValued: false
    )
    // ...
}
Type Responsibility Depends on or conforms to
SessionViewModel Search state, per-query tool and session construction, response streaming, result de-duplication SpotlightIndexer.shared, FoundationModels
SpotlightIndexer Owns the named index, decodes SampleData.plist, builds attribute sets, answers delegate callbacks NSObject, CSSearchableIndexDelegate
ContentView Browse, searching, empty, error, and results states; navigation SessionViewModel, SpotlightIndexer
SummarySection Renders the streamed response as inline Markdown let response, let isGenerating
TrailRowView, TrailImageView, TrailDetailView Present CSSearchableItem.attributeSet values CSSearchableItem

Observed: the sample declares no local protocol. SessionViewModel reads the custom distance key from the indexer when it builds fetchAttributes (LLMSearchUsingCoreSpotlightApp/Session.swift:131), so the indexer is the single definition of that custom attribute.

Access control

Symbol Access Verified effect Likely rationale
ContentView.viewModel, allTrails (LLMSearchUsingCoreSpotlightApp/ContentView.swift:13) private @State Only ContentView can reach its model and browse list Inference: the view is the owner; children get values, not the model.
SessionViewModel state properties (LLMSearchUsingCoreSpotlightApp/Session.swift:18) implicit internal Any module type can write them; ContentView writes hasSearched and binds prompt Inference: needed for the binding; it leaves the view model without a single-writer guarantee.
searchResultsTask, isOnDevice, instructions, makeSpotlightTool, makeSession, listenForSearchResults, streamResponse (LLMSearchUsingCoreSpotlightApp/Session.swift:25, LLMSearchUsingCoreSpotlightApp/Session.swift:140) private The public surface is run() and reset() Inference: keeps prompt engineering and task lifetime inside the view model.
SpotlightIndexer.init (LLMSearchUsingCoreSpotlightApp/Indexer.swift:55) private override Only shared can exist Enforces one delegate for the one named index.
SpotlightIndexer.imageNames (LLMSearchUsingCoreSpotlightApp/Indexer.swift:40) private(set) Readable by views; writable only by the indexer Inference: lookup data is derived from indexing, not edited by UI.
TrailData (LLMSearchUsingCoreSpotlightApp/Indexer.swift:15) private struct (file-scope private behaves as fileprivate) Visible only in Indexer.swift Inference: the plist schema is an indexer detail.

Reference code

LLMSearchUsingCoreSpotlightApp/Session.swift:88 — the view model’s two public operations

    func reset() {
        searchResultsTask?.cancel()
        results = []
        response = ""
        error = nil
        isGenerating = false
        hasSearched = false
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
First-launch indexing gate SpotlightIndexer.indexIfNeeded() Skips indexing when fetchLastClientState returns state; indexAllItems() writes a one-byte client state in endBatch (LLMSearchUsingCoreSpotlightApp/Indexer.swift:68, LLMSearchUsingCoreSpotlightApp/Indexer.swift:84).
Plist-to-attribute mapping SpotlightIndexer.makeAttributeSet(from:) Converts duration hours to seconds and stores distance as a custom key (LLMSearchUsingCoreSpotlightApp/Indexer.swift:161).
Prompt engineering and tool guide SessionViewModel.instructions, makeSpotlightTool() Model-facing text and search strategy live with the session that uses them.
Result de-duplication listenForSearchResults(from:) A local seen set filters by uniqueIdentifier before appending (LLMSearchUsingCoreSpotlightApp/Session.swift:181).
UI state selection ContentView.body One if/else if chain chooses browse, searching, no-results, error, or results (LLMSearchUsingCoreSpotlightApp/ContentView.swift:19).
Error wording Error.displayMessage One extension used by the view model’s catch (LLMSearchUsingCoreSpotlightApp/Session.swift:193).

Design patterns

Pattern Source evidence Purpose or tradeoff
Model-View-ViewModel ContentView owns SessionViewModel in @State and renders its state; the view model exposes run()/reset() and owns the framework calls (LLMSearchUsingCoreSpotlightApp/ContentView.swift:13, LLMSearchUsingCoreSpotlightApp/Session.swift:100) Model and tool wiring stay out of view code. The view still writes hasSearched directly.
Observable state @Observable final class SessionViewModel (LLMSearchUsingCoreSpotlightApp/Session.swift:15) SwiftUI tracks only the properties that body reads.
Delegate or data-source callbacks SpotlightIndexer: CSSearchableIndexDelegate, set as index.indexDelegate and passed as the tool’s searchableIndexDelegate (LLMSearchUsingCoreSpotlightApp/Indexer.swift:57, LLMSearchUsingCoreSpotlightApp/Session.swift:146) One object answers both index-maintenance and item-lookup callbacks.
Singleton static let shared with private override init() (LLMSearchUsingCoreSpotlightApp/Indexer.swift:36) Guarantees one owner for the named index; callers reach it globally rather than by injection.

Main application flow

Reference code

LLMSearchUsingCoreSpotlightApp/ContentView.swift:52 — search submission

            .onSubmit(of: .search) {
                Task {
                    withAnimation { viewModel.hasSearched = true }
                    await viewModel.run()
                }
            }

LLMSearchUsingCoreSpotlightApp/Session.swift:109 — one search run

    func run() async {
        searchResultsTask?.cancel()
        results = []
        response = ""
        error = nil
        isGenerating = true

        let tool = makeSpotlightTool()
        let session = makeSession(tool: tool)
        searchResultsTask = listenForSearchResults(from: tool)

        await streamResponse(from: session)
        isGenerating = false
    }

LLMSearchUsingCoreSpotlightApp/Session.swift:189 — streamed response

    private func streamResponse(from session: LanguageModelSession) async {
        do {
            for try await chunk in session.streamResponse(to: prompt) {
                response = chunk.content
            }
        } catch {
            self.error = error.displayMessage
        }
    }

Observed: isGenerating returns to false when the stream ends, but the stored listener task is not cancelled until the next run() or reset(), so late tool results can still be appended.

Naming conventions

  • Types: role suffixes match SwiftUI and Core Spotlight vocabulary: SessionViewModel, SpotlightIndexer, ContentView, TrailDetailView, TrailRowView, TrailImageView, SummarySection, SearchingView. The decoding struct is TrailData.
  • Methods: factories use make… (makeSpotlightTool, makeSession, makeAttributeSet(from:)); long-lived consumers use listenFor… and stream…; index operations use index… and create… (indexIfNeeded, indexAllItems, createSearchableItems(identifiers:)).
  • Properties: Booleans use is…/has… (isGenerating, hasSearched, isOnDevice).
  • Files: one primary type per file, except ContentView.swift (five small views) and Session.swift, which is named after the session it manages rather than its type.

Architecture takeaways

  • A language-model tool can reuse the app’s existing index delegate: SpotlightIndexer serves both Core Spotlight maintenance callbacks and SpotlightSearchTool lookups.
  • Building the tool and session per query is a simple way to guarantee fresh model context; only the results listener needs a stored, cancellable handle.
  • SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor makes main-actor isolation the default, so the code marks only the exceptions (nonisolated delegate methods) and hops back explicitly.
  • The schema appears twice, as attribute-set code and as prompt prose; keep them together when adapting the sample.
  • The outer submit task is unstored, so overlapping searches are not cancelled; a production version would retain and cancel it.

Source map

Source file Relevant symbols
LLMSearchUsingCoreSpotlightApp/LLMSearchUsingCoreSpotlightApp.swift LLMSearchUsingCoreSpotlightApp
LLMSearchUsingCoreSpotlightApp/ContentView.swift ContentView, viewModel, allTrails, enrichedResults, SummarySection, SearchingView, TrailImageView, TrailRowView
LLMSearchUsingCoreSpotlightApp/Session.swift SessionViewModel, run(), reset(), makeSpotlightTool(), makeSession(tool:), listenForSearchResults(from:), streamResponse(from:), instructions
LLMSearchUsingCoreSpotlightApp/Indexer.swift SpotlightIndexer, shared, distanceAttributeKey, indexIfNeeded(), indexAllItems(), createSearchableItems(identifiers:), makeAttributeSet(from:), TrailData
LLMSearchUsingCoreSpotlightApp/Error+DisplayMessage.swift Error.displayMessage
LLMSearchUsingCoreSpotlightApp/TrailDetailView.swift TrailDetailView
LLMSearchUsingCoreSpotlight.entitlements Empty entitlements dictionary
LLMSearchUsingCoreSpotlight.xcodeproj/project.pbxproj SWIFT_DEFAULT_ACTOR_ISOLATION, SDKROOT, TARGETED_DEVICE_FAMILY, deployment target