FirebaseFirestore Framework Reference Stay organized with collections Save and categorize content based on your preferences.
Structures
The following structures are available globally.
A property wrapper type that marks a
DocumentReference?orString?field tobe populated with a document identifier when it is read.Apply the
@DocumentIDannotation to aDocumentReference?orString?property in aCodableobject to have it populated with the documentidentifier when it is read and decoded from Firestore.Important
The name of the property annotated with
@DocumentIDmust notmatch the name of any fields in the Firestore document being read or elsean error will be thrown. For example, if theCodableobject has aproperty namedfirstNameannotated with@DocumentID, and the Firestoredocument contains a field namedfirstName, an error will be thrown whenattempting to decode the document.Example Read:
structPlayer:Codable{@DocumentIDvarplayerID:String?varhealth: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:Tryingtoencode/decode this type using encoders/decodersotherthanFirestore.Encoderthrowsanerror.-Important:WhenwritingaCodableobjectcontainingan`@DocumentID`annotatedfield,itsvalueisignored.Thisallowsyoutoreadadocumentfromonepathandwriteitintoanotherwithoutadjustingthevaluehere.Declaration
Swift
@propertyWrapperpublicstructDocumentID<Value:DocumentIDWrappable&Codable>:StructureCodingUncodedUnkeyedextensionDocumentID:CodableextensionDocumentID:EquatablewhereValue:EquatableextensionDocumentID:HashablewhereValue:HashableWraps an
Optionalfield in aCodableobject such that when the fieldhas 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
@propertyWrapperpublicstructExplicitNull<Value>extensionExplicitNull:EquatablewhereValue:EquatableextensionExplicitNull:HashablewhereValue:HashableextensionExplicitNull:EncodablewhereValue:EncodableextensionExplicitNull:DecodablewhereValue:DecodableA property wrapper that marks an
Optional<Timestamp>field to bepopulated with a server timestamp. If aCodableobject being writtencontains anilfor an@ServerTimestamp-annotated field, it will bereplaced withFieldValue.serverTimestamp()as it is sent.Example:
structCustomModel{@ServerTimestampvarts:Timestamp?}Then writing
CustomModel(ts: nil)will tell server to filltswithcurrent timestamp.Declaration
Swift
@propertyWrapperpublicstructServerTimestamp<Value>:CodablewhereValue:ServerTimestampWrappable&CodableextensionServerTimestamp:EquatablewhereValue:EquatableextensionServerTimestamp:HashablewhereValue:HashableextensionServerTimestamp:SendablewhereValue:SendableA property wrapper that listens to a Firestore collection.
In the following example,
FirestoreQuerywill fetch all documents from thefruitscollection, filtering only documents whoseisFavouriteattributeis equal totrue, map members of result set to theFruittype, and makethem available via the wrapped valuefruits.structContentView:View{@FirestoreQuery(collectionPath:"fruits",predicates:[.whereField("isFavourite",isEqualTo:true)])varfruits:[Fruit]varbody:someView{List(fruits){fruitinText(fruit.name)}}}FirestoreQueryalso supports returning aResulttype. The.successcasereturns an array of elements, whereas the.failurecase returns an errorin case mapping the Firestore documents wasn’t successful:structContentView:View{@FirestoreQuery(collectionPath:"fruits",predicates:[.whereField("isFavourite",isEqualTo:true)])varfruitResults:Result<[Fruit],Error>varbody:someView{ifcaselet.success(fruits)=fruitResults{List(fruits){fruitinText(fruit.name)}}elseifcaselet.failure(error)=fruitResults{Text("Couldn't map data:\(error.localizedDescription)")}}Alternatively, theprojected value of the property wrapper provides access tothe
erroras well. This allows you to display a list of all successfully mappeddocuments, as well as an error message with details about the documents that couldn’tbe 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,
@FirestoreQuerysets up a snapshot listener and publishesany incoming changes via an@StateObject.The projected value of this property wrapper provides access to aconfiguration object of type
FirestoreQueryConfigurationwhich can be usedto modify the query criteria. Changing the filter predicates results in theunderlying 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(iOS14.0,macOS11.0,tvOS14.0,watchOS7.0,*)@propertyWrapper@MainActorpublicstructFirestoreQuery<T>:DynamicProperty
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-03-11 UTC.