Structures
The following structures are available globally.
-
A property wrapper type that marks a
DocumentReference?orString?field to be populated with a document identifier when it is read.Apply the
@DocumentIDannotation to aDocumentReference?orString?property in aCodableobject to have it populated with the document identifier when it is read and decoded from Firestore.-
Example Read:
struct Player: Codable { @DocumentID var playerID: String? var health: Int64 }
let p = try! await Firestore.firestore() .collection("players") .document("player-1") .getDocument(as: Player.self) print("(p.playerID!) Health: (p.health)")
// Prints: "Player: player-1, Health: 95"
- Important: Trying to encode/decode this type using encoders/decoders other than Firestore.Encoder throws an error. - Important: When writing a Codable object containing an `@DocumentID` annotated field, its value is ignored. This allows you to read a document from one path and write it into another without adjusting the value here.Declaration
Swift
@propertyWrapper public struct DocumentID<Value: DocumentIDWrappable & Codable>: StructureCodingUncodedUnkeyedextension DocumentID: Codableextension DocumentID: Equatable where Value: Equatableextension DocumentID: Hashable where Value: Hashable -
-
Wraps an
Optionalfield in aCodableobject such that when the field has anilvalue it will encode to a null value in Firestore. Normally, optional fields are omitted from the encoded document.This is useful for ensuring a field is present in a Firestore document, even when there is no associated value.
Declaration
Swift
@propertyWrapper public struct ExplicitNull<Value>extension ExplicitNull: Equatable where Value: Equatableextension ExplicitNull: Hashable where Value: Hashableextension ExplicitNull: Encodable where Value: Encodableextension ExplicitNull: Decodable where Value: Decodable -
A property wrapper that marks an
Optional<Timestamp>field to be populated with a server timestamp. If aCodableobject being written contains anilfor an@ServerTimestamp-annotated field, it will be replaced withFieldValue.serverTimestamp()as it is sent.Example:
struct CustomModel { @ServerTimestamp var ts: Timestamp? }Then writing
CustomModel(ts: nil)will tell server to filltswith current timestamp.Declaration
Swift
@propertyWrapper public struct ServerTimestamp<Value>: Codable where Value: ServerTimestampWrappable & Codableextension ServerTimestamp: Equatable where Value: Equatableextension ServerTimestamp: Hashable where Value: Hashableextension ServerTimestamp: Sendable where Value: Sendable -
A property wrapper that listens to a Firestore collection.
In the following example,
FirestoreQuerywill fetch all documents from thefruitscollection, filtering only documents whoseisFavouriteattribute is equal totrue, map members of result set to theFruittype, and make them available via the wrapped valuefruits.struct ContentView: View { @FirestoreQuery( collectionPath: "fruits", predicates: [.whereField("isFavourite", isEqualTo: true)] ) var fruits: [Fruit] var body: some View { List(fruits) { fruit in Text(fruit.name) } } }FirestoreQueryalso supports returning aResulttype. The.successcase returns an array of elements, whereas the.failurecase returns an error in case mapping the Firestore documents wasn't successful:struct ContentView: View { @FirestoreQuery( collectionPath: "fruits", predicates: [.whereField("isFavourite", isEqualTo: true)] ) var fruitResults: Result<[Fruit], Error> var body: some View { if case let .success(fruits) = fruitResults { List(fruits) { fruit in Text(fruit.name) } } else if case let .failure(error) = fruitResults { Text("Couldn't map data: \(error.localizedDescription)") } }Alternatively, the projected value of the property wrapper provides access to the
erroras well. This allows you to display a list of all successfully mapped documents, as well as an error message with details about the documents that couldn't be mapped successfully (e.g. because of a field name mismatch).struct ContentView: View { @FirestoreQuery( collectionPath: "mappingFailure", decodingFailureStrategy: .ignore ) private var fruits: [Fruit] var body: some View { VStack(alignment: .leading) { List(fruits) { fruit in Text(fruit.name) } if $fruits.error != nil { HStack { Text("There was an error") .foregroundColor(Color(UIColor.systemBackground)) Spacer() } .padding(30) .background(Color.red) } } } }Internally,
@FirestoreQuerysets up a snapshot listener and publishes any incoming changes via an@StateObject.The projected value of this property wrapper provides access to a configuration object of type
FirestoreQueryConfigurationwhich can be used to modify the query criteria. Changing the filter predicates results in the underlying snapshot listener being unregistered and a new one registered.Button("Show only Apples and Oranges") { $fruits.predicates = [.whereField("name", isIn: ["Apple", "Orange]] }This property wrapper does not support updating the
wrappedValue, i.e. you need to use Firestore's other APIs to add, delete, or modify documents.Declaration
Swift
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) @propertyWrapper @MainActor public struct FirestoreQuery<T> : DynamicProperty -
An
AggregateFunctionthat has been given an alias.Declaration
Swift
public struct AliasedAggregate -
Represents the distance measure to be used in a vector similarity search.
Declaration
Swift
public struct DistanceMeasure : Sendable, Equatable, Hashable -
An
Expressionthat has been given an alias.Declaration
Swift
public struct AliasedExpression : Selectable, SelectableWrapper, Sendable -
A
Constantis anExpressionthat represents a fixed, literal value within a Firestore pipeline.Constants are used to introduce literal values into a query, which can be useful for:- Comparing a field to a specific value in a
whereclause. - Adding new fields with fixed values using
addFields. - Providing literal arguments to functions like
sumoraverage.
Example of using a
Constantto add a new field:// Add a new field "source" with the value "manual" to each document firestore.pipeline() .collection("entries") .addFields([ Constant("manual").as("source") ])Declaration
Swift
public struct Constant : Expression, BridgeWrapper, @unchecked Sendable - Comparing a field to a specific value in a
-
An expression that represents the current document being processed.
Example:
// Define the current document as a variable "doc" firestore.pipeline().collection("books") .define([CurrentDocument().as("doc")]) // Access a field from the defined document variable .select([Variable("doc").getField("title")])Declaration
Swift
public struct CurrentDocument : Expression, BridgeWrapper -
A
Fieldis anExpressionthat represents a field in a Firestore document.It is a central component for building queries and transformations in Firestore pipelines. A
Fieldcan be used to:- Reference a document field by its name or
FieldPath. - Create complex
BooleanExpressions for filtering in awhereclause. - Perform mathematical operations on numeric fields.
- Manipulate string and array fields.
Example of creating a
Fieldand using it in awhereclause:// Reference the "price" field in a document let priceField = Field("price") // Create a query to find products where the price is greater than 100 firestore.pipeline() .collection("products") .where(priceField.greaterThan(100))Declaration
Swift
public struct Field: Expression, Selectable, BridgeWrapper, SelectableWrapper, @unchecked Sendable - Reference a document field by its name or
-
A full-text search against all indexed search fields in the document.
Note
This API is in beta.Note: This expression can only be used in the
searchstage.Example usage in a
searchstage:firestore.pipeline() .collection("restaurants") .search(query: DocumentMatches("waffles OR pancakes"))Declaration
Swift
public struct DocumentMatches : BooleanExpression, BridgeWrapper, @unchecked Sendable -
Represents the relevance score of a document against the search query.
Note
This API is in beta.Example usage:
firestore.pipeline().collection("restaurants") .search( query: "waffles OR pancakes", sort: [ Score().as("searchScore") ] )Declaration
Swift
public struct Score : Expression, BridgeWrapper, @unchecked Sendable -
A
Variableis anExpressionthat retrieves the value of a variable bound viaPipeline.define.Variables are typically defined in a
definestage and can be referenced in subsequent stages.Example:
firestore.pipeline().collection("products") .define([Field("price").multiply(0.9).as("discountedPrice")]) .where(Variable("discountedPrice") < 100) .select([Field("name"), Variable("discountedPrice")])Declaration
Swift
public struct Variable : Expression, BridgeWrapper -
An ordering for the documents in a pipeline.
Declaration
Swift
public struct Ordering : @unchecked Sendable -
A direction to order results in.
Declaration
Swift
public struct Direction : Sendable, Equatable, Hashable -
Undocumented
Declaration
Swift
public struct PipelineResult : @unchecked Sendable -
A
PipelineSourceis the entry point for building a Firestore pipeline. It allows you to specify the source of the data for the pipeline, which can be a collection, a collection group, a list of documents, or the entire database.Declaration
Swift
@available(iOS 13, tvOS 13, macOS 10.15, watchOS 7, *) public struct PipelineSource : @unchecked Sendable -
Undocumented
Declaration
Swift
public struct TimeGranularity : Sendable, Equatable, Hashable -
Undocumented
Declaration
Swift
public struct TimePart : Sendable, Equatable, Hashable -
Undocumented
Declaration
Swift
public struct TimeUnit : Sendable, Equatable, Hashable