Compose SwiftData Filters Without One Giant Predicate
An events screen starts with a simple rule: show upcoming events. Then it needs events created by the current user, events from their groups, an archive toggle, and a search field.
Soon the predicate has more parentheses than the feature description. One misplaced condition can hide a user’s own event just because it has no group.
Foundation’s Predicate(all:) and Predicate(any:) let us assemble smaller predicates. We will use them to build a SwiftData list whose filters can change independently, while keeping the intended logic visible.
These two initializers require iOS 27 or macOS 27 or later. The example below is an iOS 27 SwiftUI screen, built with Xcode 27 and Swift 6.4. Selecting Swift 6 language mode does not make the initializers available on older operating systems. If you support older versions, keep your existing supported predicate construction for that path.
Write the rule before the macro
Our rule is:
(created by this user OR belongs to one of their groups)
AND starts after the cutoff
AND is not archived, when hiding archives
AND matches the search text, when the search is nonempty
The parentheses matter. An event with no group can still belong to its creator. An event in a matching group must still pass the date and search filters. A signed-out screen should return no events.
This builds on Keith Harrison’s discussion of predicates for parent relationships: unwrap an optional parent deliberately and capture filter inputs before entering the macro. We are adding composition, changing UI inputs, and tests for the combined rule.
The widely viewed relationship-query question on Stack Overflow already has answers, including capturing a persistent identifier. A more specific optional-organization question describes the ownership-or-membership rule and a failed forced unwrap. Optional relationships were manageable before OS 27; the new convenience here is assembling a collection of predicates.
Keep the model small
Download the complete sample and tests, or put the following Swift blocks, in order, into one file in an iOS 27 SwiftUI app. The final block replaces the app’s generated App declaration. The download also includes a seeded test host so there is data to filter immediately.
import Foundation
import SwiftData
import SwiftUI
@Model
final class EventGroup {
var groupID: Int
@Relationship(deleteRule: .nullify, inverse: \Event.group)
var events: [Event] = []
init(groupID: Int) {
self.groupID = groupID
}
}
@Model
final class Event {
var eventID: Int
var name: String
var creatorID: Int
var startsAt: Date
var isArchived: Bool
var group: EventGroup?
init(
eventID: Int,
name: String,
creatorID: Int,
startsAt: Date,
isArchived: Bool = false,
group: EventGroup? = nil
) {
self.eventID = eventID
self.name = name
self.creatorID = creatorID
self.startsAt = startsAt
self.isArchived = isArchived
self.group = group
}
}
These integer IDs stand in for identifiers from your app’s domain. Keep each event ID unique and each group ID associated with one group in your import or creation layer; this sample does not implement an importer or add uniqueness constraints. eventID gives sorting a stable final tie-breaker. It is separate from SwiftData’s own model identity.
Deleting a group nullifies the relationship. Its events remain stored, and their creators can still see them if the other filters match. This is a local store example, not a CloudKit schema.
Build one snapshot of the filters
Use ordinary values to describe the requested result. The snapshot does not hold an observable session object or reach into mutable UI state while constructing the macro expression.
struct EventFilter {
let viewerID: Int?
let groupIDs: [Int]
let after: Date
let hidesArchived: Bool
let search: String
func predicate() -> Predicate<Event> {
guard let viewerID else {
return #Predicate<Event> { _ in false }
}
let ids = groupIDs
let cutoff = after
let term = search.trimmingCharacters(in: .whitespacesAndNewlines)
let owned = #Predicate<Event> {
$0.creatorID == viewerID
}
let inGroup = #Predicate<Event> { event in
if let group = event.group {
ids.contains(group.groupID)
} else {
false
}
}
var required: [Predicate<Event>] = [
Predicate(any: [owned, inGroup]),
#Predicate<Event> { $0.startsAt > cutoff }
]
if hidesArchived {
required.append(#Predicate<Event> { !$0.isArchived })
}
if !term.isEmpty {
required.append(#Predicate<Event> {
$0.name.localizedStandardContains(term)
})
}
return Predicate(all: required)
}
}
any represents the two alternative ways an event becomes relevant. all combines that relevance test with every active restriction. Adding an optional filter means appending another required predicate; it does not mean rewriting the ownership rule.
Unwrapping event.group only inside inGroup keeps a missing relationship from vetoing owned. An empty groupIDs array matches no groups, but it still allows the user’s own events. Duplicate IDs do not change membership. The signed-out guard returns an explicit false predicate rather than relying on the behavior of an empty composition.
The time rule is deliberately strictly after the cutoff: an event starting exactly at that instant is excluded. If your product wants to include that boundary, use >= and change the boundary test too. Whitespace-only search behaves like an empty search; otherwise we use Foundation’s localized substring operation.
These are presentation filters over data already available to the app. They do not authorize access to server records or remove another account’s cached data on sign-out. Keep those responsibilities in the session and storage layers.
Give the changing query a child view
Apple’s WWDC26 SwiftData code-along constructs a query in a child view’s initializer, using inputs from its parent. That fits our snapshot: the parent owns the controls, and the child receives the values needed for this query.
struct FilteredEvents: View {
@Query private var events: [Event]
init(filter: EventFilter) {
_events = Query(
filter: filter.predicate(),
sort: [
SortDescriptor(\Event.startsAt),
SortDescriptor(\Event.eventID)
]
)
}
var body: some View {
EventResults(
events: events,
fetchFailed: _events.fetchError != nil
)
}
}
struct EventResults: View {
let events: [Event]
let fetchFailed: Bool
var body: some View {
if fetchFailed {
ContentUnavailableView(
"Could not load events",
systemImage: "exclamationmark.triangle",
description: Text("The current filters could not be applied.")
)
} else if events.isEmpty {
ContentUnavailableView(
"No matching events",
systemImage: "calendar"
)
} else {
List(events) { event in
VStack(alignment: .leading) {
Text(event.name)
Text(event.startsAt, format: .dateTime.month().day().hour().minute())
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
}
}
The order of those branches matters. Query.fetchError must be read within body. Apple documents that a failed fetch retains the previous successful results. Showing those rows beneath newly changed filters would imply they match the new request. Here, an error replaces the results, even if the array still contains events.
Keep error and empty states separate. “No matching events” means a successful query found nothing; it should not mean the database could not answer. In a shipping app, also report the underlying error through your existing diagnostics. A retry button alone cannot repair an unsupported predicate.
Let the parent own the controls
struct EventsScreen: View {
let viewerID: Int?
let groupIDs: [Int]
@State private var search = ""
@State private var hidesArchived = true
@State private var cutoff = Date.now
var body: some View {
VStack {
TextField("Search events", text: $search)
.textFieldStyle(.roundedBorder)
.padding(.horizontal)
Toggle("Hide archived", isOn: $hidesArchived)
.padding(.horizontal)
FilteredEvents(filter: EventFilter(
viewerID: viewerID,
groupIDs: groupIDs,
after: cutoff,
hidesArchived: hidesArchived,
search: search
))
}
.navigationTitle("Upcoming events")
.toolbar {
Button("Refresh time") {
cutoff = .now
}
}
}
}
When a control changes, SwiftUI evaluates the parent with its new state and constructs the child query from the new snapshot. Pass updated viewerID and groupIDs from your session owner in the same way. Do not seed them into private @State inside the child’s initializer and expect later parent values to replace that state.
The cutoff is a snapshot too. A query with a captured Date does not become a clock because time passes. This sample updates it when the user taps Refresh time. Choose an explicit refresh policy for your app, such as returning to the foreground, and test it. A search keystroke should not silently move the time boundary.
The example queries on each edit. For a large store, measure actual typing and fetch behavior before adding debouncing or indexes. Composition improves how we express the rule; it is not a performance benchmark.
Attach a container
For a new local demo, replace the generated app entry point with this block. It opens a persistent store and shows a separate startup failure if the container cannot be created.
@main
struct EventFilterDemoApp: App {
private let container: Result<ModelContainer, Error>
init() {
container = Result {
let schema = Schema([EventGroup.self, Event.self])
let configuration = ModelConfiguration(
schema: schema,
cloudKitDatabase: .none
)
return try ModelContainer(for: schema, configurations: configuration)
}
}
var body: some Scene {
WindowGroup {
switch container {
case .success(let container):
NavigationStack {
EventsScreen(viewerID: 10, groupIDs: [7])
}
.modelContainer(container)
case .failure:
ContentUnavailableView(
"Could not open the event store",
systemImage: "externaldrive.badge.exclamationmark"
)
}
}
}
}
The copied app starts empty and uses a fixed demo user. Insert your own sample events into its model context, or run the download’s seeded host. In an existing app, reuse its container and session inputs instead of adding a second app entry point or a separate store. Startup recovery and account management are outside this filtering example.
Test combinations against the store
A predicate can compile and evaluate in memory while still containing an expression the persistent store cannot translate. Predicate(all:) is not a permission slip for arbitrary Swift inside a database query. Test the actual fetch, including the optional relationship.
The download contains a disk-backed fixture and an independent, ordinary-Swift filtering oracle. It saves events, opens the store again, and compares fetched IDs across combinations of viewer, group IDs, search, and archive visibility. These are the cases worth keeping when adapting it:
| Case | Expected result |
|---|---|
| Owned event with no group | Included if its date and optional filters match |
| Empty group selection | Own events remain eligible |
| Matching group, different creator | Included only if the other filters also match |
| No signed-in viewer | No results |
| Event starts exactly at the cutoff | Excluded with the strict > rule |
| Group deleted and store reopened | Former membership no longer matches; ownership can still match |
| Equal start dates | Event IDs determine the final order |
| Fetch failure with previously loaded rows | Error presentation replaces the rows |
The five final Swift blocks were compiled with Xcode 27.0 / Swift 6.4, in Swift 6 language mode with warnings as errors, under both ordinary and MainActor default isolation. The disk checks passed on macOS 27.0.1 using separate processes and on iOS 27 Simulator using reopened containers within one process. Native UI tests in both modes exercised search, archive visibility, changing account/group inputs, saved edits, and the captured cutoff followed by Refresh time.
The error test supplies an explicit failure flag to EventResults while keeping previously loaded rows. It verifies their replacement by the error UI; it does not induce a database failure or independently prove SwiftData’s documented result-retention behavior. These checks cover a local store, not CloudKit or a physical device.
Keep the alternative ways to match inside any, and the restrictions that apply to every match inside all. The next filter can be another small predicate with a clear place in the rule.