Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
161: Querying with SwiftData Predicates
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
isRareproperty must betrue. - The
pricemust be greater than500.0.
Additionally, ensure the results are sorted by price in descending order (most expensive first) using a FetchDescriptor.
There are no comments for now.