Contents

init(filter:sort:transaction:)

Create a query with a predicate, and a list of sort descriptors.

Declaration

@MainActor @preconcurrency init(filter: Predicate<Element>? = nil, sort descriptors: [SortDescriptor<Element>] = [], transaction: Transaction? = nil) where Result == [Element]

Parameters

  • filter:

    A predicate on Element

  • descriptors:

    Sort orders for the result.

  • 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 {
    // Favorite recipes sorted by date of creation
    @Query(
        filter: #Predicate { $0.isFavorite == true },
        sort: [SortDescriptor(\.dateCreated)]
    )
    var favoriteRecipes: [Recipe]

    var body: some View {
        List(favoriteRecipes) { RecipeDetails($0) }
    }
}

See Also

Creating a query