Our basic SwiftData query looks like this:
@Query(sort: \Prospect.name) var prospects: [Prospect]
By default that will load all Prospect
model objects, sorting them by name, and while that's fine for the Everyone tab, it's not enough for the other two.
In our app, we have three instances of ProspectsView
that vary only according to the FilterType
property that gets passed in from our tab view. We’re already using that to set the title of each view, but we can also use it to filter our query.
Yes, we already have a default query in place, but if we add an initializer we can override that when a filter is set.
Add this initializer to ProspectsView
now:
init(filter: FilterType) {
self.filter = filter
if filter != .none {
let showContactedOnly = filter == .contacted
_prospects = Query(filter: #Predicate {
$0.isContacted == showContactedOnly
}, sort: [SortDescriptor(\Prospect.name)])
}
}
We've looked at creating queries manually previously, but there is one line that really stands out:
let showContactedOnly = filter == .contacted
If that made you do a double take, break it down into two parts. First, this check:
filter == .contacted
That will return true if filter
is equal to .contacted
, or false otherwise. And now this part:
let showContactedOnly =
That will assign the result of filter == .contacted
to a new constant called showContactedOnly
. So, if we read the whole line, it means "set showContactedOnly
to true if our filter is set to .contacted
." This makes our SwiftData predicate easy, because we can compare that constant directly against isContacted
.
With that initializer in place, we can now create a List
to loop over the resulting array. This will show both the title and email address for each prospect using a VStack
– replace the existing text view in ProspectsView
with this:
List(prospects) { prospect in
VStack(alignment: .leading) {
Text(prospect.name)
.font(.headline)
Text(prospect.emailAddress)
.foregroundStyle(.secondary)
}
}
If you run the app again you’ll see things are starting to look much better.
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.