Filter Data - SwiftUI
On this page
Observe in SwiftUI Views
The @ObservedResults
property wrapper used in the examples on this page
is intended for use in a SwiftUI View. If you want to observe results
in a view model instead, register a change listener.
Search an SDK Collection
The Swift SDK allows you to extend .searchable. When you use ObservedResults to query a realm, you can specify collection and keypath in the result set to mark it as searchable.
The collection is the bound collection represented by your ObservedResults
query. In this example, it is the dogs
variable that represents the
collection of all Dog objects in the database.
The keypath is the object property that you want to search. In this
example, we search the dogs collection by dog name. The SDK's
.searchable
implementation only supports keypaths with String
types.
struct SearchableDogsView: View { Dog.self) var dogs ( private var searchFilter = "" var body: some View { NavigationView { // The list shows the dogs in the realm. List { ForEach(dogs) { dog in DogRow(dog: dog) } } .searchable(text: $searchFilter, collection: $dogs, keyPath: \.name) { ForEach(dogs) { dogsFiltered in Text(dogsFiltered.name).searchCompletion(dogsFiltered.name) } } } } }
Filter or Query a Database with ObservedResults
The @ObservedResults property wrapper
opens a database and returns all objects of the specified type. However, you
can filter or query @ObservedResults
to use only a subset of the objects
in your view.
Tip
See also:
For more information about the query syntax and types of queries that the SDK supports, refer to: Read and Type-Safe and NSPredicate Queries - Swift SDK.
Query with the Swift Query API
To use @ObservedResults
with the Swift Query API, pass a query in a closure as an argument to
where
:
struct FilterDogsViewTypeSafeQuery: View { Dog.self, where: ( { $0.weight > 40 } )) var dogs ( var body: some View { NavigationView { // The list shows the dogs in the realm. List { ForEach(dogs) { dog in DogRow(dog: dog) } } } } }
Filter with an NSPredicate
To filter @ObservedResults
using the NSPredicate Query API, pass an NSPredicate as an argument to filter
:
struct FilterDogsViewNSPredicate: View { Dog.self, filter: NSPredicate(format: "weight > 40")) var dogs ( var body: some View { NavigationView { // The list shows the dogs in the realm. List { ForEach(dogs) { dog in DogRow(dog: dog) } } } } }
Section Results
The @ObservedSectionedResults
property wrapper opens a database and returns all objects of the specified type,
divided into sections by the specified key path. Similar to
@ObservedResults
above, you can filter or query @ObservedSectionedResults
to use only a subset of the objects in your view:
Dog.self, ( sectionKeyPath: \.firstLetter, where: ( { $0.weight > 40 } )) var dogs