Learn Courses My Dashboard

Why am I receiving an incorrect array count when using “.count” to return a Swift subscript count?

I am currently creating an iOS application that allows users to add in a number of different products, each of which are added into a Google Firestore array, similarly to the example below.


  • [0] “Product Name: Test, Listing Price: 5, A brief description: test, Product URL: Test, Listing active until: 20/06/2021 12:19”
  • [1] “Product Name: Test2, Listing Price: 5, A brief description: test2, Product URL: Test2, Listing active until: 26/06/2021 12:19”

As part of this, I am using the following Swift code to return a count of subscripts for the users list of products (in the case of the example above, 2) to allow them to see how many products they currently have listed.

  let db = Firestore.firestore()
  let user = Auth.auth().currentUser

  db.collection("users").getDocuments { (snapshot, error) in
     if let error = error {
          } else {
         for document in snapshot!.documents {
              let data = document.data()
              let userId = data["uid"] as! String
              if userId == user?.uid {

let group_array = document["product"] as? [String] ?? [""]
let productCount = (group_array.count)

However once a user initially signs up for an account and is redirected to a welcome page, for some reason whenever the above syntax is used, it returns a “1”, indicating that the user has a product added, shown in the below example (but worth noting that the “1” value is shown in numerous other locations around the application where a user can view their current product count.

enter image description here

However the user has no products in their dataset on the database, as shown below and therefore because the application believes the group_array.count value is > 0, it returns an unexpected nil when attempting to view this item, crashing the application and therefore preventing me from adding the application onto TestFlight.

enter image description here

During runtime analysis, a single product shows, but returns as an empty string whereas this doesn’t exist in the database.

enter image description here

I currently have all of the Firestore related pods in my Xcode project set to the same iOS 14.5 deployment target, and when I add another product using the newly created account and then proceed to delete that product, the application begins to work again as expected, with the count reflecting the correct ‘product’ subscript total.

Is this a problem with my pod configuration, my application or with the Google Firestore SDK? If so, are there any fixes or guidance available to resolve/fix this please?

its probably because you always have a fallback of [""] which is exactly 1 record (an empty string)… i suggest to remove this and see how it crashes, it should not crash if the array is empty btw

1 Like