A property wrapper type that marks a DocumentReference? or String? field to
be populated with a document identifier when it is read.
Apply the @DocumentID annotation to a DocumentReference? or String?
property in a Codable object to have it populated with the document
identifier when it is read and decoded from Firestore.
Important
The name of the property annotated with @DocumentID must not
match the name of any fields in the Firestore document being read or else
an error will be thrown. For example, if the Codable object has a
property named firstName annotated with @DocumentID, and the Firestore
document contains a field named firstName, an error will be thrown when
attempting to decode the document.
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:Tryingtoencode/decode this type using encoders/decodersotherthanFirestore.Encoderthrowsanerror.-Important:WhenwritingaCodableobjectcontainingan`@DocumentID`annotatedfield,itsvalueisignored.Thisallowsyoutoreadadocumentfromonepathandwriteitintoanotherwithoutadjustingthevaluehere.
Wraps an Optional field in a Codable object such that when the field
has a nil value 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.
A property wrapper that marks an Optional<Timestamp> field to be
populated with a server timestamp. If a Codable object being written
contains a nil for an @ServerTimestamp-annotated field, it will be
replaced with FieldValue.serverTimestamp() as it is sent.
A property wrapper that listens to a Firestore collection.
In the following example, FirestoreQuery will fetch all documents from the
fruits collection, filtering only documents whose isFavourite attribute
is equal to true, map members of result set to the Fruit type, and make
them available via the wrapped value fruits.
FirestoreQuery also supports returning a Result type. The .success case
returns an array of elements, whereas the .failure case returns an error
in case mapping the Firestore documents wasn’t successful:
Alternatively, the projected value of the property wrapper provides access to
the error as 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).
structContentView:View{@FirestoreQuery(collectionPath:"mappingFailure",decodingFailureStrategy:.ignore)privatevarfruits:[Fruit]varbody:someView{VStack(alignment:.leading){List(fruits){fruitinText(fruit.name)}if$fruits.error!=nil{HStack{Text("There was an error").foregroundColor(Color(UIColor.systemBackground))Spacer()}.padding(30).background(Color.red)}}}}
Internally, @FirestoreQuery sets 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 FirestoreQueryConfiguration which 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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-03-11 UTC."],[],[],null,["# FirebaseFirestore Framework Reference\n\nStructures\n==========\n\nThe following structures are available globally.\n- `\n ``\n ``\n `\n\n ### [DocumentID](/docs/reference/swift/firebasefirestore/api/reference/Structs/DocumentID)\n\n `\n ` \n A property wrapper type that marks a `DocumentReference?` or `String?` field to\n be populated with a document identifier when it is read.\n\n Apply the `@DocumentID` annotation to a `DocumentReference?` or `String?`\n property in a `Codable` object to have it populated with the document\n identifier when it is read and decoded from Firestore. \n Important\n\n The name of the property annotated with `@DocumentID` must not\n match the name of any fields in the Firestore document being read or else\n an error will be thrown. For example, if the `Codable` object has a\n property named `firstName` annotated with `@DocumentID`, and the Firestore\n document contains a field named `firstName`, an error will be thrown when\n attempting to decode the document.\n - Example Read:\n\n struct Player: Codable {\n @DocumentID var playerID: String?\n var health: Int64\n }\n\n let p = try! await Firestore.firestore()\n .collection(\"players\")\n .document(\"player-1\")\n .getDocument(as: Player.self)\n print(\"(p.playerID!) Health: (p.health)\")\n\n // Prints: \"Player: player-1, Health: 95\" \n\n\n - Important: Trying to encode/decode this type using encoders/decoders other than\n Firestore.Encoder throws an error.\n\n - Important: When writing a Codable object containing an `@DocumentID` annotated field,\n its value is ignored. This allows you to read a document from one path and\n write it into another without adjusting the value here.\n\n #### Declaration\n\n Swift \n\n @propertyWrapper\n public struct DocumentID\u003cValue: /docs/reference/swift/firebasefirestore/api/reference/Protocols/DocumentIDWrappable & Codable\u003e:\n StructureCodingUncodedUnkeyed\n\n extension DocumentID: Codable\n\n extension DocumentID: Equatable where Value: Equatable\n\n extension DocumentID: Hashable where Value: Hashable\n\n- `\n ``\n ``\n `\n\n ### [ExplicitNull](/docs/reference/swift/firebasefirestore/api/reference/Structs/ExplicitNull)\n\n `\n ` \n Wraps an `Optional` field in a `Codable` object such that when the field\n has a `nil` value it will encode to a null value in Firestore. Normally,\n optional fields are omitted from the encoded document.\n\n This is useful for ensuring a field is present in a Firestore document,\n even when there is no associated value. \n\n #### Declaration\n\n Swift \n\n @propertyWrapper\n public struct ExplicitNull\u003cValue\u003e\n\n extension ExplicitNull: Equatable where Value: Equatable\n\n extension ExplicitNull: Hashable where Value: Hashable\n\n extension ExplicitNull: Encodable where Value: Encodable\n\n extension ExplicitNull: Decodable where Value: Decodable\n\n- `\n ``\n ``\n `\n\n ### [ServerTimestamp](/docs/reference/swift/firebasefirestore/api/reference/Structs/ServerTimestamp)\n\n `\n ` \n A property wrapper that marks an `Optional\u003cTimestamp\u003e` field to be\n populated with a server timestamp. If a `Codable` object being written\n contains a `nil` for an `@ServerTimestamp`-annotated field, it will be\n replaced with [FieldValue.serverTimestamp()](/docs/reference/swift/firebasefirestore/api/reference/Classes/FieldValue#/c:objc(cs)FIRFieldValue(cm)fieldValueForServerTimestamp) as it is sent.\n\n Example: \n\n struct CustomModel {\n @ServerTimestamp var ts: Timestamp?\n }\n\n Then writing `CustomModel(ts: nil)` will tell server to fill `ts` with\n current timestamp. \n\n #### Declaration\n\n Swift \n\n @propertyWrapper\n public struct ServerTimestamp\u003cValue\u003e: Codable\n where Value: /docs/reference/swift/firebasefirestore/api/reference/Protocols/ServerTimestampWrappable & Codable\n\n extension ServerTimestamp: Equatable where Value: Equatable\n\n extension ServerTimestamp: Hashable where Value: Hashable\n\n extension ServerTimestamp: Sendable where Value: Sendable\n\n- `\n ``\n ``\n `\n\n ### [FirestoreQuery](/docs/reference/swift/firebasefirestore/api/reference/Structs/FirestoreQuery)\n\n `\n ` \n A property wrapper that listens to a Firestore collection.\n\n In the following example, `FirestoreQuery` will fetch all documents from the\n `fruits` collection, filtering only documents whose `isFavourite` attribute\n is equal to `true`, map members of result set to the `Fruit` type, and make\n them available via the wrapped value `fruits`. \n\n struct ContentView: View {\n @FirestoreQuery(\n collectionPath: \"fruits\",\n predicates: [.whereField(\"isFavourite\", isEqualTo: true)]\n ) var fruits: [Fruit]\n\n var body: some View {\n List(fruits) { fruit in\n Text(fruit.name)\n }\n }\n }\n\n `FirestoreQuery` also supports returning a `Result` type. The `.success` case\n returns an array of elements, whereas the `.failure` case returns an error\n in case mapping the Firestore documents wasn't successful: \n\n struct ContentView: View {\n @FirestoreQuery(\n collectionPath: \"fruits\",\n predicates: [.whereField(\"isFavourite\", isEqualTo: true)]\n ) var fruitResults: Result\u003c[Fruit], Error\u003e\n\n var body: some View {\n if case let .success(fruits) = fruitResults {\n List(fruits) { fruit in\n Text(fruit.name)\n }\n } else if case let .failure(error) = fruitResults {\n Text(\"Couldn't map data: \\(error.localizedDescription)\")\n }\n }\n\n Alternatively, the *projected value* of the property wrapper provides access to\n the `error` as well. This allows you to display a list of all successfully mapped\n documents, as well as an error message with details about the documents that couldn't\n be mapped successfully (e.g. because of a field name mismatch). \n\n struct ContentView: View {\n @FirestoreQuery(\n collectionPath: \"mappingFailure\",\n decodingFailureStrategy: .ignore\n ) private var fruits: [Fruit]\n\n var body: some View {\n VStack(alignment: .leading) {\n List(fruits) { fruit in\n Text(fruit.name)\n }\n if $fruits.error != nil {\n HStack {\n Text(\"There was an error\")\n .foregroundColor(Color(UIColor.systemBackground))\n Spacer()\n }\n .padding(30)\n .background(Color.red)\n }\n }\n }\n }\n\n Internally, `@FirestoreQuery` sets up a snapshot listener and publishes\n any incoming changes via an `@StateObject`.\n\n The projected value of this property wrapper provides access to a\n configuration object of type `FirestoreQueryConfiguration` which can be used\n to modify the query criteria. Changing the filter predicates results in the\n underlying snapshot listener being unregistered and a new one registered. \n\n Button(\"Show only Apples and Oranges\") {\n $fruits.predicates = [.whereField(\"name\", isIn: [\"Apple\", \"Orange]]\n }\n\n This property wrapper does not support updating the `wrappedValue`, i.e.\n you need to use Firestore's other APIs to add, delete, or modify documents. \n\n #### Declaration\n\n Swift \n\n @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)\n @propertyWrapper\n @MainActor\n public struct FirestoreQuery\u003cT\u003e : DynamicProperty"]]