Contents

init(filter:sort:order:animation:)

Creates 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, animation: Animation) where Result == [Element], Value : Comparable

Parameters

  • filter:

    A predicate on Element

  • sort:

    Key path to property used for sorting.

  • order:

    Whether to sort in forward or reverse order.

  • animation:

    The animation 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) }
    }
}

See Also

Creating a query