In SwiftUI, how do you use the searchable modifier to filter a list of notes, and what decides where the search field appears?
answer
- you own the query storage
- a binding, then a derived array
- attach near a navigation container
- placement is a request, not an order
- scopes follow the searchable modifier
basics
~20 sKeep the query in your own @State, bind it with .searchable(text:) on a view inside a NavigationStack or NavigationSplitView, and filter the rows from that text; platform, modifier position and the placement request decide where the field appears.
solid answer
~40 sSwiftUI does no filtering for me: `searchable(text:placement:prompt:)` only binds a search field to a `String` I own, usually `@State private var query = ""`. Each keystroke writes through the binding, the body re-runs, and a computed property such as `notes.filter { $0.title.localizedStandardContains(query) }` feeds the `List`. The field appears in the toolbar when the modifier is on a `NavigationStack` or `NavigationSplitView` or a view inside one; on iPad, attaching it to a column's view puts it in that column. The `placement:` argument, such as `.navigationBarDrawer(displayMode: .always)`, is a request SwiftUI ignores when it cannot satisfy it. For categories I add `searchScopes(_:scopes:)` after `.searchable`, and for costly searches I wait for `onSubmit(of: .search)`.
code
swift · 29 linesstruct Note: Identifiable {
let id = UUID()
var title: String
}
struct NoteSearchSuggestions: View {
let notes: [Note]
let recentQueries: [String]
@State private var query = ""
var body: some View {
NavigationStack {
List(notes.filter { query.isEmpty || $0.title.localizedStandardContains(query) }) { note in
Text(note.title)
}
.navigationTitle("Notes")
.searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
.searchSuggestions {
ForEach(recentQueries, id: \.self) { recent in
Label(recent, systemImage: "clock")
.searchCompletion(recent)
}
}
.onSubmit(of: .search) {
// Record the submitted query as a recent search here.
}
}
}
}go deeper
Recall the three parts: a String in @State, its binding passed to .searchable(text:), and a filtered array the List shows.
Explain where the field lands, why placement is only a request, how scopes and suggestions attach to the searchable before them, and the empty-query guard.
Show judgment on cost: in-memory filtering per keystroke versus waiting for onSubmit(of: .search), caching, and an empty-results state for people.
Weigh where search state should live when several screens share it, and whether search runs locally or on a server, against responsiveness and cost.
## The division of labour The **`searchable`** family of modifiers puts a **search field** into your interface. It does not know anything about your data. Apple's article "Performing a search operation" spells out the contract: you "create storage for the query text and present it with a searchable view modifier", and because you manage the storage, you react to its changes yourself. So a search feature in SwiftUI always has three parts: 1. **Storage** for the query, usually `@State private var query = ""` in the view that owns the screen, or a property on a model shared between views. 2. **A binding** to that storage passed to `.searchable(text: $query)`. As people type, SwiftUI writes the text through the binding. 3. **A derived collection** that your `List` or `ForEach` displays, computed from the full data and the current query. ## Filtering from the text ```swift struct NotesSearchView: View { let notes: [Note] @State private var query = "" @State private var scope = NoteScope.all private var visibleNotes: [Note] { notes.filter { note in (scope == .all || note.isPinned) && (query.isEmpty || note.title.localizedStandardContains(query)) } } var body: some View { NavigationStack { List(visibleNotes) { note in Text(note.title) } .navigationTitle("Notes") .searchable(text: $query, prompt: "Search notes") .searchScopes($scope) { Text("All").tag(NoteScope.all) Text("Pinned").tag(NoteScope.pinned) } .overlay { if visibleNotes.isEmpty && !query.isEmpty { ContentUnavailableView.search(text: query) } } } } } ``` Points worth saying out loud in an interview: - The **empty query returns everything**. Without that guard, the list is blank until someone types. - `localizedStandardContains` is the Foundation method intended for user-facing search matching, rather than a plain `contains`, which compares characters exactly. - `ContentUnavailableView.search(text:)` (iOS 17) is the system's "No Results" view, so you do not hand-build one. - The filter is a **computed property**, not a second `@State` array, so it can never drift out of sync with the data or the query. ## Where the field lands Apple's article "Adding a search interface to your app" says to apply a searchable modifier "to a NavigationSplitView or NavigationStack, or to a view inside one of these", after which "a search field then appears in the toolbar". The exact spot depends on three things: | Factor | Effect | |---|---| | Platform | iPhone shows it in the navigation bar; macOS at the trailing edge of the window toolbar | | Where the modifier sits | On a split view, iPad puts it in the first or second column; on a column's view, in that column | | `placement:` argument | A `SearchFieldPlacement` request such as `.automatic`, `.navigationBarDrawer(displayMode:)`, `.sidebar` or `.toolbar` | The placement is a **preference**. If SwiftUI cannot satisfy it, for example `.sidebar` on a modifier that is not applied to a split view, it "relies instead on its automatic placement rules". On iPhone, `.navigationBarDrawer(displayMode: .always)` asks for the field in the navigation bar's drawer with the `.always` display mode, instead of leaving the display mode to the system. On iOS 26 and later, a `DefaultToolbarItem` with the search kind lets you choose where the system's search item sits among your toolbar items. ## Scopes, suggestions and tokens All three are modifiers or parameters that act on the **nearest searchable modifier before them**, so the order matters. - **Scopes**: `searchScopes(_:scopes:)` (iOS 16) binds a `Hashable` value and shows a picker; the tags must have the same type as the binding. By default iOS shows the picker once people start typing; `searchScopes(_:activation:_:)` (iOS 16.4) changes that with `.onSearchPresentation` or `.onTextEntry`. - **Suggestions**: `searchSuggestions(_:)` (iOS 16) lists views below the field; give each one `searchCompletion(_:)` so tapping it fills in the query. A suggestion without `searchCompletion` is shown but does not react to taps. The older `searchable(text:placement:prompt:suggestions:)` form is marked for deprecation in favour of this modifier. - **Tokens**: `searchable(text:tokens:placement:prompt:token:)` takes a binding to an array of `Identifiable` values that appear as chips at the start of the field, so you combine discrete terms with free text. ## When filtering is expensive Filtering an in-memory array on every keystroke is fine for hundreds of notes. Apple's guidance for costly searches, such as network requests or complex predicates, is to prefetch and cache, reduce how often you update, or wait for submission: `.onSubmit(of: .search) { ... }` runs when people press Return in the search field. Running an asynchronous search that restarts as the text changes belongs with the material on view tasks and cancellation. ## Common mistakes - Expecting `.searchable` to filter the list by itself. - Storing the filtered array in its own `@State` and forgetting to recompute it when the data changes. - Placing `.searchScopes` before `.searchable`, so it has no searchable modifier to attach to. - Attaching `.searchable` to a view outside any navigation container, against Apple's guidance to apply it to a `NavigationStack` or `NavigationSplitView` or a view inside one.
- Why does a search suggestion row ignore taps, and how do you fix it?A view inside `searchSuggestions` only becomes actionable when you attach `searchCompletion(_:)` to it, giving the string, or token, that SwiftUI should place in the field when it is chosen. Without it, Apple's documentation says the view is displayed but does not react to taps or clicks. Add `.searchCompletion("apple")` to each row that should fill in the query.
- How do search tokens change the filter you write?With `searchable(text:tokens:placement:prompt:token:)` the query becomes two inputs: free text plus an array of `Identifiable` token values the field shows as chips. Your derived collection must combine both, for example keeping notes that match the text and carry every selected tag, and the empty case is now both inputs empty, not just an empty string.
- The searchable modifier filters the list's rows automatically
- A placement argument always forces the field to that exact spot
- searchScopes works wherever it sits relative to searchable
- Suggestion rows fill the field without searchCompletion
- Every keystroke should trigger a network request without any throttling