Skip to Content
Course content

161: Querying with SwiftData Predicates

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're working at a massive archive library. You have millions of documents stored in rows of cabinets. If a researcher comes to you and asks for "every letter written by Abraham Lincoln between 1863 and 1865," you aren't going to drag every single piece of paper out of the cabinets, bring it to your desk, and read it just to see if it fits. You'd be there for a century.

Instead, you use the library's index. You tell the system exactly what you're looking for—the author and the date range—and the system only hands you the specific folders that match. You've essentially created a "filter" that happens before the data ever hits your desk.

In SwiftData, that index filter is the #Predicate. It allows you to tell the underlying database exactly which records you want, so your app doesn't waste memory loading 10,000 objects when you only actually need five of them.

Defining Your Search Criteria with #Predicate

In the old days of Core Data, we had to use NSPredicate, which felt like writing code in a different language using strings. It was fragile; if you mistyped a property name in a string, the app would just crash at runtime. SwiftData fixes this with the #Predicate macro, which gives us full type safety. If you try to filter a Book model by a property that doesn't exist, the compiler will yell at you immediately.

Let's say we have a Book model. I want to find all books written by "J.R.R. Tolkien" that were published after 1950. Here is how I'd set that up:

let authorName = "J.R.R. Tolkien"
let minYear = 1950

let predicate = #Predicate<Book> { book in
    book.author == authorName && book.year > minYear
}

Notice that I'm using a closure-like syntax. Inside those braces, I'm describing the "ideal" object. The && (AND) and || (OR) operators work exactly as you'd expect. One thing I want to warn you about: you can't put complex custom functions inside a predicate. The macro has to be able to translate your Swift code into a database query (SQL). If you try to call a fancy helper method you wrote in another file, the compiler will let you know it can't translate that into a query.

Connecting the Predicate to your FetchDescriptor

A predicate on its own is just a set of rules; it doesn't actually do anything until you attach it to a FetchDescriptor. This is where you tell SwiftData, "Use these rules to go grab the data."

I usually handle this inside a function where I can pass in different search terms. Here is how that looks in practice:

func fetchRecentBooks(by author: String) throws -> [Book] {
    let predicate = #Predicate<Book> { book in
        book.author == author && book.year > 2020
    }
    
    var descriptor = FetchDescriptor<Book>(predicate: predicate)
    descriptor.sortBy = [SortDescriptor(\.year, order: .reverse)]
    
    return try modelContext.fetch(descriptor)
}

I've added a SortDescriptor here because filtering and sorting almost always go hand-in-hand. Filtering narrows down the pile, and sorting puts them in the order you actually want to see them.

Handling String Searches and Collections

You'll often run into the need to search for a keyword rather than an exact match. If you want to find all books that have "Lord" anywhere in the title, you can't use ==. Instead, you'll use contains.

Here's a quick example of a more flexible search:

let searchTerm = "Lord"
let predicate = #Predicate<Book> { book in
    book.title.contains(searchTerm)
}

This is incredibly powerful for building search bars. As the user types, you simply update the searchTerm variable, recreate the predicate, and re-run your fetch. Because the filtering happens at the database level, it stays snappy even as your library grows from ten books to ten thousand.




📋 Practical Task

Implement a "High-Value Rare Book" Filter

You are building a management app for a rare book dealer. You have a Book model with the following properties: title: String, author: String, price: Double, and isRare: Bool.

Your task is to write a function called fetchPremiumRareBooks() that returns an array of Book objects. The query must use a #Predicate to filter for books that meet both of these criteria:

  • The isRare property must be true.
  • The price must be greater than 500.0.

Additionally, ensure the results are sorted by price in descending order (most expensive first) using a FetchDescriptor.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.