FirebaseFirestoreSwift Framework Reference Stay organized with collections Save and categorize content based on your preferences.
Structures
The following structures are available globally.
A value that is populated in Codable objects with the
DocumentReferenceof the current document by the Firestore.Decoder when a document is read.If the field name used for this type conflicts with a read document field,an error is thrown. For example, if a custom object has a field
firstNameannotated with@DocumentID, and there is a property from the documentnamedfirstNameas well, an error is thrown when you try to read thedocument.When writing a Codable object containing an
@DocumentIDannotated field,its value is ignored. This allows you to read a document from one path andwrite it into another without adjusting the value here.NOTE: Trying to encode/decode this type using encoders/decoders other thanFirestore.Encoder leads to an error.
Declaration
Swift
@propertyWrapperpublicstructDocumentID<Value:DocumentIDWrappable&Codable>:DocumentIDProtocol,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:HashableA 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 docments 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,*)@propertyWrapperpublicstructFirestoreQuery<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 2022-05-11 UTC.