init(filter:sort:order:transaction:)
Create a query with a predicate, a key path to a property for sorting, and the order to sort by.
Declaration
@MainActor @preconcurrency init<Value>(filter: Predicate<Element>? = nil, sort keyPath: KeyPath<Element, Value?>, order: SortOrder = .forward, transaction: Transaction? = nil) where Result == [Element], Value : ComparableParameters
- filter:
A predicate on
Element - sort:
Key path to property used for sorting.
- order:
Whether to sort in forward or reverse order.
- transaction:
A transaction to use for user interface changes that result from changes to the fetched results.
Discussion
Use Query within a view by wrapping the variable for the query’s result:
struct RecipeList: View {
// Recipes sorted by date of creation
@Query(sort: \.dateCreated)
var favoriteRecipes: [Recipe]
var body: some View {
List(favoriteRecipes) { RecipeDetails($0) }
}
}