Contents

EntityPropertyQuery

An interface for locating entities by matching values against one or more of their properties.

Declaration

protocol EntityPropertyQuery : EntityQuery

Mentioned in

Overview

EntityPropertyQuery provides an EntityQuery with the ability to query instances according to its traits as they are modeled through query properties and their corresponding comparators.

At runtime, entities(matching:mode:sortedBy:limit:) receives an array of ComparatorMappingType instances - a type of your choice that represents the different comparator mappings given by the user - and is responsible for fetching entities matching those comparators.

The properties property on a EntityPropertyQuery contains the set of EntityQueryPropertys the query accepts. When declaring each property’s set of supported EntityQueryComparators, you will supply a closure that will transform a runtime user-supplied value into an instance of ComparatorMappingType.

The AppIntents runtime will invoke query comparator mapping closures for each comparator included in the user request, gather their output ComparatorMappingType values, and then invoke the entities function. It is then up to you to retrieve entities matching those comparators, using whichever backend (in-memory lookup, CoreData, remote network call, …) suits your application. For example, consider the following simplified AppEntity for a photo:

class MyPhoto: AppEntity {
    @Property(title: "Date taken")
    let takenAt: Date

    @Property(title: "Tags")
    let tags: [String]
}

The following example shows how you would build a EntityPropertyQuery that allows the user to query for photos taken:

  • Before a certain date

  • After a certain date

  • Containing a given tag

In entities you want to retrieve photos through a network request, so you supply mapping closures returning URLQueryItem instances for each EntityQueryComparator. Then you can use those URLQueryItem in entities to construct the correct URL to fetch entities.

struct MyPhotoQuery: EntityPropertyQuery {
   static var properties = QueryProperties {
       Property(\.$takenAt) {
           LessThanMapping { URLQueryItem(name: "takenBefore", value: $0) }
           GreaterThanMapping { URLQueryItem(name: "takenAfter": value: $0) }
       }
       Property(\.$tags) {
           ContainsComparator { URLQueryItem(name: "tagsContains", value: $0) }
       }
   }

   func entities(
       matching comparators: [URLQueryItem],
       mode: ComparatorMode,
       sortedBy: [Sort<MyPhoto>],
       limit: Int?
   ) async throws -> [MyPhoto] {
       let components = URLComponents()
       components.queryItems = comparators
       let url = components.url(relativeTo: "https://myphotosbackend.com/photos")

       return try await PhotosBackend.fetch(url: url)
   }
}

Topics

Specifying the queryable properties

Sorting the results

Searching for entities

Type Properties

See Also

Property-matched queries