Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

Filter Data - SwiftUI

On this page

  • Observe in SwiftUI Views
  • Search an SDK Collection
  • Filter or Query a Database with ObservedResults
  • Query with the Swift Query API
  • Filter with an NSPredicate
  • Section Results

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.

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 {
@ObservedResults(Dog.self) var dogs
@State 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)
}
}
}
}
}

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.

To use @ObservedResults with the Swift Query API, pass a query in a closure as an argument to where:

struct FilterDogsViewTypeSafeQuery: View {
@ObservedResults(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)
}
}
}
}
}

To filter @ObservedResults using the NSPredicate Query API, pass an NSPredicate as an argument to filter:

struct FilterDogsViewNSPredicate: View {
@ObservedResults(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)
}
}
}
}
}

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:

@ObservedSectionedResults(Dog.self,
sectionKeyPath: \.firstLetter,
where: ( { $0.weight > 40 } )) var dogs
← Write Data