Home > Software design >  Can you upload a custom struct to a Firestore using Swift
Can you upload a custom struct to a Firestore using Swift

Time:07-01

I am creating an app where I have a custom struct called Piece. This piece has a string name, a string location, and a map/ dict. Is there a way to save this to Firestore?

Example code but this is what I will need to upload.

struct Piece {
    name = 2222
    location = "Drawer-1"
    quantities = ["blue" : 1, "red" : 3]
}

This is my first post ever so sorry if I do things wrong format-wise.

CodePudding user response:

yes - this is possible. I wrote a long blog post about this: Mapping Firestore Data in Swift - The Comprehensive Guide.

In your case, here is how you would do this:

First, make your struct (and the Quantity struct) codable:

struct Piece: Codable {
  @DocumentID var id: String?
  var name: Int // are you sure that a field containing a number like 2222 should be called "name"?
  var location: String
  var quantities: [Quantity]
}

struct Quantity: Codable {
  var color: String
  var amount: Int
}

Then, create a class for accessing Firestore. You can name it PieceStore or PieceRepository, whatever you like.

class PieceStore {
  func addPiece(piece: Piece) {
    let collectionRef = db.collection("pieces")
    do {
      let newDocReference = try collectionRef.addDocument(from: piece)
      print("Piece stored with new document reference: \(newDocReference)")
    }
    catch {
      print(error)
    }
  }
}

See the blog post for more details about fetching data using one-time fetches and snapshot listeners (which will give you that cool real-time sync that Firestore is famous for).

  • Related