FirebaseFirestore Framework Reference

Structures

The following structures are available globally.

  • A property wrapper type that marks aDocumentReference? orString? field tobe populated with a document identifier when it is read.

    Apply the@DocumentID annotation to aDocumentReference? orString?property in aCodable object to have it populated with the documentidentifier when it is read and decoded from Firestore.

    Important

    The name of the property annotated with@DocumentID must notmatch the name of any fields in the Firestore document being read or elsean error will be thrown. For example, if theCodable object has aproperty namedfirstName annotated 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>:StructureCodingUncodedUnkeyed
    extensionDocumentID:Codable
    extensionDocumentID:EquatablewhereValue:Equatable
    extensionDocumentID:HashablewhereValue:Hashable
  • Wraps anOptional field in aCodable object such that when the fieldhas anil 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.

    Declaration

    Swift

    @propertyWrapperpublicstructExplicitNull<Value>
    extensionExplicitNull:EquatablewhereValue:Equatable
    extensionExplicitNull:HashablewhereValue:Hashable
    extensionExplicitNull:EncodablewhereValue:Encodable
    extensionExplicitNull:DecodablewhereValue:Decodable
  • A property wrapper that marks anOptional<Timestamp> field to bepopulated with a server timestamp. If aCodable object being writtencontains anil for an@ServerTimestamp-annotated field, it will bereplaced withFieldValue.serverTimestamp() as it is sent.

    Example:

    structCustomModel{@ServerTimestampvarts:Timestamp?}

    Then writingCustomModel(ts: nil) will tell server to fillts withcurrent timestamp.

    Declaration

    Swift

    @propertyWrapperpublicstructServerTimestamp<Value>:CodablewhereValue:ServerTimestampWrappable&Codable
    extensionServerTimestamp:EquatablewhereValue:Equatable
    extensionServerTimestamp:HashablewhereValue:Hashable
    extensionServerTimestamp:SendablewhereValue:Sendable
  • A property wrapper that listens to a Firestore collection.

    In the following example,FirestoreQuery will fetch all documents from thefruits collection, filtering only documents whoseisFavourite attributeis equal totrue, map members of result set to theFruit type, 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)}}}

    FirestoreQuery also supports returning aResult type. The.success casereturns an array of elements, whereas the.failure case 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 totheerror as 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,@FirestoreQuery sets up a snapshot listener and publishesany incoming changes via an@StateObject.

    The projected value of this property wrapper provides access to aconfiguration object of typeFirestoreQueryConfiguration which 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 thewrappedValue, 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.